public void onStartPage(PdfWriter writer, Document document) {
      try {
        PdfPTable table = new PdfPTable(1);
        table.setWidthPercentage(100);

        PdfPTable tab1 = new PdfPTable(1);

        // sub table 2
        PdfPTable subtab2 = new PdfPTable(1);
        subtab2.setWidthPercentage(100);
        subtab2.addCell(
            printStr("SINGAPORE CONSULATE-GENERAL HONG KONG", 1, 25, true, PdfPCell.NO_BORDER, 1));
        subtab2.addCell(printStr("Tel:2527 2212", 1, 25, true, PdfPCell.NO_BORDER, 1));
        PdfPCell subcel2 = new PdfPCell(subtab2);
        subcel2.setColspan(1);
        subcel2.setHorizontalAlignment(subcel2.ALIGN_LEFT);
        subcel2.setBorder(subcel2.NO_BORDER);
        subcel2.setPaddingBottom(0.0f);
        tab1.addCell(subcel2);

        float[] widths = {80};
        tab1.setWidths(widths);
        PdfPCell cel1 = new PdfPCell(tab1);
        cel1.setColspan(1);
        cel1.setHorizontalAlignment(cel1.ALIGN_LEFT);
        cel1.setBorder(cel1.NO_BORDER);
        cel1.setPaddingBottom(0.0f);
        cel1.setFixedHeight(120f);
        table.addCell(cel1);
        // col headers
        float[] widths4 = {80};
        table.setWidths(widths4);
        Rectangle page = document.getPageSize();
        table.setTotalWidth(page.width() - document.leftMargin() - document.rightMargin());
        table.writeSelectedRows(0, -1, 20, page.height() - 20 + table.getTotalHeight() - 90, cb);

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
예제 #2
0
  public void createPdf() throws ClassNotFoundException, SQLException {
    /*Declaramos documento como un objeto Document
    Asignamos el tamaño de hoja y los margenes */
    Document documento = new Document(PageSize.A4.rotate(), 1, 1, 20, 36);

    // writer es declarado como el método utilizado para escribir en el archivo
    PdfWriter writer = null;

    try {
      // Obtenemos la instancia del archivo a utilizar

      String filename =
          "C:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/documentos/reporteAutorizacion.pdf";

      File fichero = new File(filename);

      if (fichero.exists()) {
        System.out.println("El fichero  existe222222222");
        fichero.delete();
        System.out.println("El fichero elimino");
      } else {
        System.out.println("el fichero no existe");
      }

      writer = PdfWriter.getInstance(documento, new FileOutputStream(filename));

    } catch (Exception ex) {
      System.out.println("NO creooooo");
      ex.getMessage();
    }

    // Declaramos una instancia de los eventos en HeaderFooter
    HeaderFooter event = new HeaderFooter();
    writer.setPageEvent(event);

    // Agregamos un titulo al archivo
    documento.addTitle("ARCHIVO PDF");

    // Agregamos el autor del archivo
    documento.addAuthor("PROVIAS NACIONAL");

    // Abrimos el documento para edición
    documento.open();
    try {
      // Declaramos un texto como Paragraph
      // Le podemos dar formado como alineación, tamaño y color a la fuente.
      Paragraph title1 = new Paragraph();
      title1.setAlignment(Element.ALIGN_CENTER);

      PdfPTable ta1 = new PdfPTable(2);
      ta1.setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      PdfPCell cel1 = new PdfPCell();
      com.lowagie.text.Image image =
          com.lowagie.text.Image.getInstance("D:/Provias/images/imgExports.jpg");
      // image.setWidthPercentage(500);
      cel1.addElement(image);
      cel1.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel1.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel1.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel1);
      PdfPCell cel2 = new PdfPCell();

      cel2.addElement(
          new Phrase(
              "Reporte de Autorizaciones Especiales",
              FontFactory.getFont(
                  FontFactory.HELVETICA, 12, Font.BOLD, new CMYKColor(0, 0, 0, 100))));
      cel2.setFixedHeight(90);
      cel2.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel2.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel2.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel2);

      float[] columnWidths1 = new float[] {180f, 100f};
      ta1.setWidths(columnWidths1);
      title1.add(ta1);

      // Agregamos el texto al documento
      documento.add(title1);

      // Agregamos un salto de linea
      documento.add(new Paragraph(" "));

      // Agregamos la tabla al documento haciendo
      // la llamada al método tabla()
      documento.add(tabla());
    } catch (Exception ex) {
      System.out.println("Por!!");
      ex.getMessage();
    }

    documento.close(); // Cerramos el documento
    writer.close(); // Cerramos writer
  }
  @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);
    }
  }