コード例 #1
0
ファイル: PDF.java プロジェクト: ringgi/railo
  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));
        }
      }
    }
  }
コード例 #2
0
  /** @see com.lowagie.toolbox.AbstractTool#execute() */
  public void execute() {
    try {
      if (getValue("odd") == null)
        throw new InstantiationException("You need to choose a sourcefile for the odd pages");
      File odd_file = (File) getValue("odd");
      if (getValue("even") == null)
        throw new InstantiationException("You need to choose a sourcefile for the even pages");
      File even_file = (File) getValue("even");
      if (getValue("destfile") == null)
        throw new InstantiationException("You need to choose a destination file");
      File pdf_file = (File) getValue("destfile");
      RandomAccessFileOrArray odd = new RandomAccessFileOrArray(odd_file.getAbsolutePath());
      RandomAccessFileOrArray even = new RandomAccessFileOrArray(even_file.getAbsolutePath());
      Image img = TiffImage.getTiffImage(odd, 1);
      Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file));
      document.open();
      PdfContentByte cb = writer.getDirectContent();
      int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even));
      for (int c = 0; c < count; ++c) {
        try {
          Image imgOdd = TiffImage.getTiffImage(odd, c + 1);
          Image imgEven = TiffImage.getTiffImage(even, count - c);
          document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight()));
          document.newPage();
          imgOdd.setAbsolutePosition(0, 0);
          cb.addImage(imgOdd);
          document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight()));
          document.newPage();
          imgEven.setAbsolutePosition(0, 0);
          cb.addImage(imgEven);

        } catch (Exception e) {
          System.out.println("Exception page " + (c + 1) + " " + e.getMessage());
        }
      }
      odd.close();
      even.close();
      document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #3
0
 public void execute(PdfContentByte cb, BaseFont bf) {
   String t = sanitizeText(getText());
   Barcode128 code128 = new Barcode128();
   code128.setGenerateChecksum(true);
   code128.setCode(t);
   if (!isShowText()) {
     code128.setFont(null);
   }
   code128.setBarHeight(getSize());
   Image img = code128.createImageWithBarcode(cb, getColor(), getColor());
   // float w = code128.getBarcodeSize().width() / 2;
   img.setAbsolutePosition(getOffsetX(), getOffsetY());
   img.setRotationDegrees(getDirection());
   try {
     cb.addImage(img);
   } catch (DocumentException e) {
     // Do nothing for the time being...
   }
 }
コード例 #4
0
  private void savePDF() {
    File f =
        new File(
            logSource.getFile(".")
                + "/"
                + logSource.name()
                + "-"
                + messageName
                + "."
                + varName
                + "."
                + curEntity
                + "-"
                + cmapCombo.getSelectedItem().toString()
                + ".pdf");

    Rectangle pageSize = PageSize.A4.rotate();
    try {
      FileOutputStream out = new FileOutputStream(f);

      Document doc = new Document(pageSize);
      PdfWriter writer = PdfWriter.getInstance(doc, out);
      doc.open();
      PdfContentByte cb = writer.getDirectContent();
      java.awt.Graphics2D g2 = cb.createGraphicsShapes(pageSize.getWidth(), pageSize.getHeight());
      int width = (int) pageSize.getWidth();
      int height = (int) pageSize.getHeight();

      int prevWidth = defaultWidth;
      int prevHeight = defaultHeight;

      defaultWidth = width;
      defaultHeight = height;

      BufferedImage img = bufImage;

      com.lowagie.text.Image pdfImage = com.lowagie.text.Image.getInstance(writer, img, 0.8f);
      pdfImage.setAbsolutePosition(0, 0);
      cb.addImage(pdfImage);

      double maxX = dd.maxX + 5;
      double maxY = dd.maxY + 5;
      double minX = dd.minX - 5;
      double minY = dd.minY - 5;

      // width/height
      double dx = maxX - minX;
      double dy = maxY - minY;

      double ratio1 = (double) defaultWidth / (double) defaultHeight;
      double ratio2 = dx / dy;

      if (ratio2 < ratio1) dx = dy * ratio1;
      else dy = dx / ratio1;

      drawLegend(g2, (ColorMap) cmapCombo.getSelectedItem(), 0);

      doc.close();
      defaultWidth = prevWidth;
      defaultHeight = prevHeight;

      JOptionPane.showMessageDialog(this, "PDF saved to log directory");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
ファイル: PDF.java プロジェクト: ringgi/railo
  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));
        }
      }
    }
  }
コード例 #6
0
  /** Demonstrates the use of ColumnText. */
  @Test
  public void main() throws Exception {

    // step 1: creation of a document-object
    Document document = new Document();

    // step 2: creation of the writer
    PdfWriter writer =
        PdfWriter.getInstance(document, PdfTestBase.getOutputStream("columnirregular.pdf"));

    // step 3: we open the document
    document.open();

    // step 4:
    // we grab the contentbyte and do some stuff with it
    PdfContentByte cb = writer.getDirectContent();

    PdfTemplate t = cb.createTemplate(600, 800);
    Image caesar = Image.getInstance(PdfTestBase.RESOURCES_DIR + "caesar_coin.jpg");
    cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
    t.setGrayFill(0.75f);
    t.moveTo(310, 112);
    t.lineTo(280, 60);
    t.lineTo(340, 60);
    t.closePath();
    t.moveTo(310, 790);
    t.lineTo(310, 710);
    t.moveTo(310, 580);
    t.lineTo(310, 122);
    t.stroke();
    cb.addTemplate(t, 0, 0);

    ColumnText ct = new ColumnText(cb);
    ct.addText(
        new Phrase(
            "GALLIA est omnis divisa in partes tres, quarum unam incolunt Belgae, aliam Aquitani, tertiam qui ipsorum lingua Celtae, nostra Galli appellantur.  Hi omnes lingua, institutis, legibus inter se differunt. Gallos ab Aquitanis Garumna flumen, a Belgis Matrona et Sequana dividit. Horum omnium fortissimi sunt Belgae, propterea quod a cultu atque humanitate provinciae longissime absunt, minimeque ad eos mercatores saepe commeant atque ea quae ad effeminandos animos pertinent important, proximique sunt Germanis, qui trans Rhenum incolunt, quibuscum continenter bellum gerunt.  Qua de causa Helvetii quoque reliquos Gallos virtute praecedunt, quod fere cotidianis proeliis cum Germanis contendunt, cum aut suis finibus eos prohibent aut ipsi in eorum finibus bellum gerunt.\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "[Eorum una, pars, quam Gallos obtinere dictum est, initium capit a flumine Rhodano, continetur Garumna flumine, Oceano, finibus Belgarum, attingit etiam ab Sequanis et Helvetiis flumen Rhenum, vergit ad septentriones. Belgae ab extremis Galliae finibus oriuntur, pertinent ad inferiorem partem fluminis Rheni, spectant in septentrionem et orientem solem. Aquitania a Garumna flumine ad Pyrenaeos montes et eam partem Oceani quae est ad Hispaniam pertinet; spectat inter occasum solis et septentriones.]\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "Apud Helvetios longe nobilissimus fuit et ditissimus Orgetorix.  Is M. Messala, [et P.] M.  Pisone consulibus regni cupiditate inductus coniurationem nobilitatis fecit et civitati persuasit ut de finibus suis cum omnibus copiis exirent:  perfacile esse, cum virtute omnibus praestarent, totius Galliae imperio potiri.  Id hoc facilius iis persuasit, quod undique loci natura Helvetii continentur:  una ex parte flumine Rheno latissimo atque altissimo, qui agrum Helvetium a Germanis dividit; altera ex parte monte Iura altissimo, qui est inter Sequanos et Helvetios; tertia lacu Lemanno et flumine Rhodano, qui provinciam nostram ab Helvetiis dividit.  His rebus fiebat ut et minus late vagarentur et minus facile finitimis bellum inferre possent; qua ex parte homines bellandi cupidi magno dolore adficiebantur.  Pro multitudine autem hominum et pro gloria belli atque fortitudinis angustos se fines habere arbitrabantur, qui in longitudinem milia passuum CCXL, in latitudinem CLXXX patebant.\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "His rebus adducti et auctoritate Orgetorigis permoti constituerunt ea quae ad proficiscendum pertinerent comparare, iumentorum et carrorum quam maximum numerum coemere, sementes quam maximas facere, ut in itinere copia frumenti suppeteret, cum proximis civitatibus pacem et amicitiam confirmare.  Ad eas res conficiendas biennium sibi satis esse duxerunt; in tertium annum profectionem lege confirmant.  Ad eas res conficiendas Orgetorix deligitur.  Is sibi legationem ad civitates suscipit.  In eo itinere persuadet Castico, Catamantaloedis filio, Sequano, cuius pater regnum in Sequanis multos annos obtinuerat et a senatu populi Romani amicus appellatus erat, ut regnum in civitate sua occuparet, quod pater ante habuerit; itemque Dumnorigi Haeduo, fratri Diviciaci, qui eo tempore principatum in civitate obtinebat ac maxime plebi acceptus erat, ut idem conaretur persuadet eique filiam suam in matrimonium dat.  Perfacile factu esse illis probat conata perficere, propterea quod ipse suae civitatis imperium obtenturus esset:  non esse dubium quin totius Galliae plurimum Helvetii possent; se suis copiis suoque exercitu illis regna conciliaturum confirmat.  Hac oratione adducti inter se fidem et ius iurandum dant et regno occupato per tres potentissimos ac firmissimos populos totius Galliae sese potiri posse sperant.\n",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));
    ct.addText(
        new Phrase(
            "Ea res est Helvetiis per indicium enuntiata.  Moribus suis Orgetoricem ex vinculis causam dicere coegerunt; damnatum poenam sequi oportebat, ut igni cremaretur.  Die constituta causae dictionis Orgetorix ad iudicium omnem suam familiam, ad hominum milia decem, undique coegit, et omnes clientes obaeratosque suos, quorum magnum numerum habebat, eodem conduxit; per eos ne causam diceret se eripuit.  Cum civitas ob eam rem incitata armis ius suum exequi conaretur multitudinemque hominum ex agris magistratus cogerent, Orgetorix mortuus est; neque abest suspicio, ut Helvetii arbitrantur, quin ipse sibi mortem consciverit.",
            FontFactory.getFont(FontFactory.HELVETICA, 12)));

    float[] left1 = {70, 790, 70, 60};
    float[] right1 = {300, 790, 300, 700, 240, 700, 240, 590, 300, 590, 300, 106, 270, 60};
    float[] left2 = {320, 790, 320, 700, 380, 700, 380, 590, 320, 590, 320, 106, 350, 60};
    float[] right2 = {550, 790, 550, 60};

    int status = 0;
    int column = 0;
    while ((status & ColumnText.NO_MORE_TEXT) == 0) {
      if (column == 0) {
        ct.setColumns(left1, right1);
        column = 1;
      } else {
        ct.setColumns(left2, right2);
        column = 0;
      }
      status = ct.go();
      ct.setYLine(790);
      ct.setAlignment(Element.ALIGN_JUSTIFIED);
      status = ct.go();
      if ((column == 0) && ((status & ColumnText.NO_MORE_COLUMN) != 0)) {
        document.newPage();
        cb.addTemplate(t, 0, 0);
        cb.addImage(caesar, 100, 0, 0, 100, 260, 595);
      }
    }

    // step 5: we close the document
    document.close();
  }
コード例 #7
0
  public void onEndPage(PdfWriter pdfWriter, Document document) {
    pageNum++; // 页面计数
    if (needNotFootAndHead && pageNum >= needNotFootAndHeadPageNum) {
      return;
    }

    PdfContentByte pdfContByte = pdfWriter.getDirectContent();
    pdfContByte.saveState();
    pdfContByte.setGState(pdfGState);
    pdfContByte.setFontAndSize(baseFont, 48);
    pdfContByte.endText();

    Image barCodeImge = code39.createImageWithBarcode(pdfContByte, null, null);

    try {
      pdfContByte.addImage(
          headerImage,
          headerImage.getWidth() / 2,
          0,
          0,
          headerImage.getHeight() / 2,
          document.left() + 65,
          document.top() + 10);
      pdfContByte.addImage(
          barCodeImge,
          barCodeImge.getWidth(),
          0,
          0,
          barCodeImge.getHeight(),
          document.left() + 35,
          document.bottom() - 26);
    } catch (Exception ex) {
      throw new ExceptionConverter(ex);
    }
    pdfContByte.restoreState();
    pdfContByte.saveState();

    String headFootText = "保险合同号:" + this.contNo;
    float headTextPos = document.top() + 10;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 10);
    pdfContByte.setTextMatrix(document.right() - 175, headTextPos);
    pdfContByte.showText(headFootText);
    pdfContByte.endText();
    pdfContByte.saveState();

    //		cell.setBorder(Rectangle.BOTTOM);

    //		String metLife = "中美大都会人寿保险有限公司";
    //		float footTextPos = document.bottom()-12;
    //		pdfContByte.beginText();
    //		pdfContByte.setFontAndSize(baseFont, 7);
    //		pdfContByte.setTextMatrix(document.left()+50, footTextPos);
    //		pdfContByte.showText(metLife);
    //		pdfContByte.endText();
    //		pdfContByte.saveState();

    String shanghaimetLife = "中美联泰大都会人寿保险有限公司";
    float shanghaifootText = document.bottom();
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.left() + 35, shanghaifootText);
    pdfContByte.showText(shanghaimetLife);
    pdfContByte.endText();
    pdfContByte.saveState();

    String shanghaimetLifeAddress = "                  联系地址:上海市黄浦区黄陂北路227号中区广场11楼";
    float shanghaifootTextAddPos = document.bottom();
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 190, shanghaifootTextAddPos);
    pdfContByte.showText(shanghaimetLifeAddress);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeAddress = "北京东城区东长安街一号东方广场东方经贸城东二办公楼12层";
    float footTextAddPos = document.bottom() - 8;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 190, footTextAddPos);
    pdfContByte.showText(metLifeAddress);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeCustSer = "客户服务热线:400 818 8168";
    float footTextCSPos = document.bottom() - 16;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 85, footTextCSPos);
    pdfContByte.showText(metLifeCustSer);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeSite = "http://www.metlife.com.cn/";
    float footTextSTPos = document.bottom() - 24;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 75, footTextSTPos);
    pdfContByte.showText(metLifeSite);
    pdfContByte.endText();
    pdfContByte.saveState();

    //		String pageNumText = "第 " + pdfWriter.getPageNumber() + " 页";
    String pageNumText = String.valueOf(pdfWriter.getPageNumber());
    float textBase = document.bottom() - 2;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 9);
    pdfContByte.setTextMatrix(document.left() + 285, textBase);
    pdfContByte.showText(pageNumText);
    pdfContByte.endText();
    pdfContByte.saveState();
  }
コード例 #8
0
  @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);
    }
  }
コード例 #9
0
ファイル: ImageMasks.java プロジェクト: kjella/iText-4.2.0
  /**
   * Applying masks to images.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {
    System.out.println("masked images");

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    try {
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("maskedImages.pdf"));

      document.open();
      Paragraph p = new Paragraph("Some text behind a masked image.");
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);

      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      document.add(p);
      PdfContentByte cb = writer.getDirectContent();
      byte maskr[] = {
        (byte) 0x3c,
        (byte) 0x7e,
        (byte) 0xe7,
        (byte) 0xc3,
        (byte) 0xc3,
        (byte) 0xe7,
        (byte) 0x7e,
        (byte) 0x3c
      };
      Image mask = Image.getInstance(8, 8, 1, 1, maskr);
      mask.makeMask();
      mask.setInverted(true);
      Image image = Image.getInstance("otsoe.jpg");
      image.setImageMask(mask);
      image.setAbsolutePosition(60, 550);
      // explicit masking
      cb.addImage(image);
      // stencil masking
      cb.setRGBColorFill(255, 0, 0);
      cb.addImage(mask, mask.getScaledWidth() * 8, 0, 0, mask.getScaledHeight() * 8, 100, 450);
      cb.setRGBColorFill(0, 255, 0);
      cb.addImage(mask, mask.getScaledWidth() * 8, 0, 0, mask.getScaledHeight() * 8, 100, 400);
      cb.setRGBColorFill(0, 0, 255);
      cb.addImage(mask, mask.getScaledWidth() * 8, 0, 0, mask.getScaledHeight() * 8, 100, 350);
      document.close();
    } catch (Exception de) {
      de.printStackTrace();
    }
  }