Example #1
0
  private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    railo.runtime.img.Image ri =
        new railo.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
Example #2
0
  public static void main(String[] args) throws Exception {
    String filePath = ReaderPdf.class.getClassLoader().getResource("pdf/pdf.pdf").getPath();

    // 待加水印的文件
    PdfReader reader = new PdfReader(filePath);

    String newFilePath = "D:/test/newPdf.pdf";
    File f = new File(newFilePath);
    if (!f.exists()) {
      f.createNewFile();
    }

    // 加完水印的文件
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFilePath));
    int total = reader.getNumberOfPages() + 1;

    PdfContentByte content;
    // 设置字体
    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

    // BaseFont baseFont =
    // BaseFont.createFont("STSong-Light",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
    // BaseFont baseFont =
    // BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
    // 水印文字
    String waterText = "------广东省云浮市闻莺路东升布艺------";
    int leng = waterText.length(); // 文字长度
    char c = 0;
    int height = 0; // 高度
    // 循环对每页插入水印
    for (int i = 1; i < total; i++) {
      // 水印的起始
      height = 500;
      content = stamper.getUnderContent(i);
      // 开始
      content.beginText();
      // 设置颜色
      content.setColorFill(Color.GRAY);
      // 设置字体及字号
      content.setFontAndSize(baseFont, 18);
      // 设置起始位置
      content.setTextMatrix(500, 780);
      // 开始写入水印
      for (int k = 0; k < leng; k++) {
        content.setTextRise(14);
        c = waterText.charAt(k);
        // 将char转成字符串
        content.showText(c + "");
        height -= 5;
      }
      content.endText();
    }
    stamper.close();
  }
Example #3
0
  private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
      throw new ApplicationException(
          "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    // image
    Image img = null;
    if (image != null) {
      railo.runtime.img.Image ri =
          railo.runtime.img.Image.createImage(pageContext, image, false, false, true);
      img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
      byte[] barr;
      try {
        Resource res = Caster.toResource(pageContext, copyFrom, true);
        barr = IOUtil.toBytes(res);
      } catch (ExpressionException ee) {
        barr = Caster.toBinary(copyFrom);
      }
      img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);
    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
      int index = position.indexOf(',');
      if (index == -1)
        throw new ApplicationException(
            "attribute [position] has a invalid value ["
                + position
                + "],"
                + "value should follow one of the following pattern [40,50], [40,] or [,50]");
      String strX = position.substring(0, index).trim();
      String strY = position.substring(index + 1).trim();
      if (!StringUtil.isEmpty(strX)) x = Caster.toIntValue(strX);
      if (!StringUtil.isEmpty(strY)) y = Caster.toIntValue(strY);
    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {

      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      if (len > 0) {
        if (x == UNDEFINED || y == UNDEFINED) {
          PdfImportedPage first = stamp.getImportedPage(reader, 1);
          if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2;
          if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2;
        }
        img.setAbsolutePosition(x, y);
        // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

      }

      // rotation
      if (rotation != 0) {
        img.setRotationDegrees(rotation);
      }

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        // print.out("op:"+opacity);
        gs1.setFillOpacity(opacity);
        // gs1.setStrokeOpacity(opacity);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
  @Override
  public String create() {

    try {
      Document document =
          new Document(
              PageSize.A4, getMarginLeft(), getMarginRight(), getMarginTop(), getMarginBottom());

      String path =
          UserDocumentHelper.createPathToDocument(
              getDocumentDir(), // PDF File を置く場所
              "診断書", // 文書名
              EXT_PDF, // 拡張子
              model.getPatientName(), // 患者氏名
              new Date()); // 日付
      // minagawa^ jdk7
      Path pathObj = Paths.get(path);
      setPathToPDF(pathObj.toAbsolutePath().toString()); // 呼び出し側で取り出せるように保存する
      // minagawa$
      // Open Document
      ByteArrayOutputStream byteo = new ByteArrayOutputStream();
      PdfWriter.getInstance(document, byteo);
      document.open();

      // Font
      baseFont = BaseFont.createFont(HEISEI_MIN_W3, UNIJIS_UCS2_HW_H, false);
      if (Project.getString(Project.SHINDANSYO_FONT_SIZE).equals("small")) {
        titleFont = new Font(baseFont, getTitleFontSize());
        bodyFont = new Font(baseFont, getBodyFontSize());
      } else {
        titleFont = new Font(baseFont, 18);
        bodyFont = new Font(baseFont, 14);
      }

      // ----------------------------------------
      // タイトル
      // ----------------------------------------
      Paragraph para = new Paragraph(DOC_TITLE, titleFont);
      para.setAlignment(Element.ALIGN_CENTER);
      document.add(para);
      document.add(new Paragraph(" "));
      document.add(new Paragraph(" "));
      document.add(new Paragraph(" "));

      // ----------------------------------------
      // 患者情報テーブル
      // ----------------------------------------
      PdfPTable pTable = new PdfPTable(new float[] {20.0f, 60.0f, 10.0f, 10.0f});
      pTable.setWidthPercentage(100.0f);

      // 患者氏名
      PdfPCell cell;
      pTable.addCell(createNoBorderCell("氏  名"));
      cell = createNoBorderCell(model.getPatientName());
      cell.setColspan(3);
      pTable.addCell(cell);

      // 生年月日 性別
      pTable.addCell(createNoBorderCell("生年月日"));
      pTable.addCell(createNoBorderCell(getDateString(model.getPatientBirthday())));
      pTable.addCell(createNoBorderCell("性別"));
      pTable.addCell(createNoBorderCell(model.getPatientGender()));

      // 住所
      pTable.addCell(createNoBorderCell("住  所"));
      cell = createNoBorderCell(model.getPatientAddress());
      cell.setColspan(3);
      pTable.addCell(cell);

      // 傷病名
      String disease = model.getItemValue(MedicalCertificateImpl.ITEM_DISEASE);
      pTable.addCell(createNoBorderCell("傷 病 名"));
      cell = createNoBorderCell(disease);
      cell.setColspan(3);
      pTable.addCell(cell);

      document.add(pTable);
      document.add(new Paragraph(" "));

      // ------------------------------------------
      // コンテントテーブル
      // ------------------------------------------
      pTable = new PdfPTable(new float[] {1.0f});
      pTable.setWidthPercentage(100.0f);
      String informed = model.getTextValue(MedicalCertificateImpl.TEXT_INFORMED_CONTENT);
      cell = createNoBorderCell(informed);
      if (Project.getString("sindansyo.font.size").equals("small")) {
        cell.setFixedHeight(250.0f); // Cell 高
      } else {
        cell.setFixedHeight(225.0f); // Cell 高
      }
      cell.setLeading(0f, 1.5f); // x 1.5 font height
      pTable.addCell(cell);
      document.add(pTable);
      document.add(new Paragraph(" "));

      // ------------------------------------------
      // 署名テーブル
      // ------------------------------------------
      // 日付
      pTable = new PdfPTable(new float[] {1.0f});
      pTable.setWidthPercentage(100.0f);

      // 上記の通り診断する
      pTable.addCell(createNoBorderCell("上記の通り診断する。"));
      // minagawa^ LSC 1.4 bug fix 文書の印刷日付 2013/06/24
      // String dateStr = getDateString(model.getConfirmed());
      String dateStr = getDateString(model.getStarted());
      // minagawa$
      pTable.addCell(createNoBorderCell(dateStr));

      // 住所 BaseFont.getWidthPoint
      String zipCode = model.getConsultantZipCode();
      String address = model.getConsultantAddress();
      //            float zipLen = baseFont.getWidthPoint(zipCode, 12.0f);
      //            float addressLen = baseFont.getWidthPoint(address, 12.0f);
      //            float padlen = addressLen-zipLen;
      //            sb = new StringBuilder();
      //            while (true) {
      //                sb.append(" ");
      //                if (baseFont.getWidthPoint(sb.toString(), 12.0f)>=padlen) {
      //                    break;
      //                }
      //            }
      //            String space = sb.toString();
      StringBuilder sb = new StringBuilder();
      sb.append(zipCode);
      cell = createNoBorderCell(sb.toString());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      sb = new StringBuilder();
      sb.append(address);
      cell = createNoBorderCell(sb.toString());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      // 病院名
      cell = createNoBorderCell(model.getConsultantHospital());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      // 電話番号
      cell = createNoBorderCell(model.getConsultantTelephone());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      // 医師
      sb = new StringBuilder();
      sb.append("医 師 ").append(model.getConsultantDoctor()).append(" 印");
      cell = createNoBorderCell(sb.toString());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);
      document.add(pTable);

      document.close();

      // // pdf content bytes
      byte[] pdfbytes = byteo.toByteArray();

      // 評価でない場合は Fileへ書き込んでリターン
      if (!ClientContext.is5mTest()) {
        // minagawa^
        //                FileOutputStream fout = new FileOutputStream(pathToPDF);
        //                FileChannel channel = fout.getChannel();
        //                ByteBuffer bytebuff = ByteBuffer.wrap(pdfbytes);
        //
        //                while(bytebuff.hasRemaining()) {
        //                    channel.write(bytebuff);
        //                }
        //                channel.close();
        Files.write(pathObj, pdfbytes);
        // minagawa$
        return getPathToPDF();
      }

      // 評価の場合は water Mark を書く
      PdfReader pdfReader = new PdfReader(pdfbytes);
      // minagawa~
      //            PdfStamper pdfStamper = new PdfStamper(pdfReader,new
      // FileOutputStream(pathToPDF));
      PdfStamper pdfStamper = new PdfStamper(pdfReader, Files.newOutputStream(pathObj));
      // minagawa$
      Image image = Image.getInstance(ClientContext.getImageResource("water-mark.png"));

      for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

        PdfContentByte content = pdfStamper.getUnderContent(i);
        image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
        image.setAbsolutePosition(0.0f, 0.0f);

        content.addImage(image);
      }

      pdfStamper.close();

      return getPathToPDF();

    } catch (IOException ex) {
      ClientContext.getBootLogger().warn(ex);
      throw new RuntimeException(ERROR_IO);
    } catch (DocumentException ex) {
      ClientContext.getBootLogger().warn(ex);
      throw new RuntimeException(ERROR_PDF);
    }
  }