Пример #1
0
  //	---------------- for footer and header....------------------
  @Override
  public void onEndPage(PdfWriter writer, Document document) {

    try {

      Rectangle page = document.getPageSize();

      // we will print the header using the code below

      PdfPTable headTable = getHeader();
      headTable.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());

      // the table is printed at the spcific location

      headTable.writeSelectedRows(0, -1, document.leftMargin(), 830, writer.getDirectContent());
      // we will print the footer using the code below

      PdfPTable footTable = getFooter();

      footTable.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());

      footTable.writeSelectedRows(
          0, -1, document.leftMargin(), document.bottomMargin() - 560, writer.getDirectContent());

    } catch (Exception ex) {

      ex.printStackTrace();
    }

    // TODO Auto-generated method stub

  }
Пример #2
0
  public static void main(String[] args) throws IOException, DocumentException {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontFamily = ge.getAvailableFontFamilyNames();
    PrintStream out1 = new PrintStream(new FileOutputStream(RESULT1));
    for (int i = 0; i < fontFamily.length; i++) {
      out1.println(fontFamily[i]);
    }
    out1.flush();
    out1.close();

    DefaultFontMapper mapper = new DefaultFontMapper();
    mapper.insertDirectory("c:/windows/fonts/");
    PrintStream out2 = new PrintStream(new FileOutputStream(RESULT2));
    for (Entry<String, BaseFontParameters> entry : mapper.getMapper().entrySet()) {
      out2.println(String.format("%s: %s", entry.getKey(), entry.getValue().fontName));
    }
    out2.flush();
    out2.close();

    float width = 150;
    float height = 150;
    Document document = new Document(new Rectangle(width, height));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT3));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Graphics2D g2d = cb.createGraphics(width, height, mapper);
    for (int i = 0; i < FONTS.length; ) {
      g2d.setFont(FONTS[i++]);
      g2d.drawString("Hello world", 5, 24 * i);
    }
    g2d.dispose();
    document.close();
  }
Пример #3
0
 /**
  * Method to export charts as PDF files using the defined path.
  *
  * @param path The filename and absolute path.
  * @param chart The JFreeChart object.
  * @param width The width of the PDF file.
  * @param height The height of the PDF file.
  * @param mapper The font mapper for the PDF file.
  * @param title The title of the PDF file.
  * @throws IOException If writing a PDF file fails.
  */
 @SuppressWarnings("deprecation")
 public static void exportPdf(
     String path, JFreeChart chart, int width, int height, FontMapper mapper, String title)
     throws IOException {
   File file = new File(path);
   FileOutputStream pdfStream = new FileOutputStream(file);
   BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream);
   Rectangle pagesize = new Rectangle(width, height);
   Document document = new Document();
   document.setPageSize(pagesize);
   document.setMargins(50, 50, 50, 50);
   document.addAuthor("OMSimulationTool");
   document.addSubject(title);
   try {
     PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput);
     document.open();
     PdfContentByte contentByte = pdfWriter.getDirectContent();
     PdfTemplate template = contentByte.createTemplate(width, height);
     Graphics2D g2D = template.createGraphics(width, height, mapper);
     Double r2D = new Rectangle2D.Double(0, 0, width, height);
     chart.draw(g2D, r2D);
     g2D.dispose();
     contentByte.addTemplate(template, 0, 0);
   } catch (DocumentException de) {
     JOptionPane.showMessageDialog(
         null,
         "Failed to write PDF document.\n" + de.getMessage(),
         "Failed",
         JOptionPane.ERROR_MESSAGE);
     de.printStackTrace();
   }
   document.close();
 }
Пример #4
0
  private static void booklet(String input) throws Exception {
    String output = input.replace(".pdf", "-booklet.pdf");
    PdfReader reader = new PdfReader(input);
    int n = reader.getNumberOfPages();
    Rectangle pageSize = reader.getPageSize(1);

    System.out.println("Input page size: " + pageSize);
    Document doc = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
    doc.open();
    splitLine(doc, writer);
    int[] pages = new int[(n + 3) / 4 * 4];
    int x = 1, y = pages.length;
    for (int i = 0; i < pages.length; ) {
      pages[i++] = y--;
      pages[i++] = x++;
      pages[i++] = x++;
      pages[i++] = y--;
    }
    PdfContentByte cb = writer.getDirectContent();
    float bottom = (doc.top() - pageSize.getHeight()) / 2 + kOffset;
    float left = doc.right() / 2 - (pageSize.getWidth() + kTextWidth) / 2 - kMargin;
    float right = doc.right() / 2 - (pageSize.getWidth() - kTextWidth) / 2 + kMargin;

    for (int i = 0; i < pages.length; ) {
      PdfImportedPage page = getPage(writer, reader, pages[i++]);
      if (page != null) cb.addTemplate(page, left, bottom);

      page = getPage(writer, reader, pages[i++]);
      if (page != null) cb.addTemplate(page, right, bottom);

      doc.newPage();
    }
    doc.close();
  }
  /**
   * Creates a PDF document.
   *
   * @param filename the path to the new PDF document
   * @throws DocumentException
   * @throws IOException
   */
  public void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Rectangle rect = new Rectangle(-595, -842, 595, 842);
    Document document = new Document(rect);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    // draw the coordinate system
    PdfContentByte canvas = writer.getDirectContent();
    canvas.moveTo(-595, 0);
    canvas.lineTo(595, 0);
    canvas.moveTo(0, -842);
    canvas.lineTo(0, 842);
    canvas.stroke();

    // read the PDF with the logo
    PdfReader reader = new PdfReader(RESOURCE);
    PdfTemplate template = writer.getImportedPage(reader, 1);
    // add it at different positions using different transformations
    canvas.addTemplate(template, 0, 0);
    canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0);
    canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f);
    canvas.addTemplate(template, 1, 0, 0.4f, 1, -750, -650);
    canvas.addTemplate(template, 0, -1, -1, 0, 650, 0);
    canvas.addTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0);
    // step 5
    document.close();
    reader.close();
  }
Пример #6
0
 private void exportGraphToPdf(mxGraph graph, String filename) {
   Rectangle bounds =
       new Rectangle(trackScheme.getGUI().graphComponent.getViewport().getViewSize());
   // step 1
   com.itextpdf.text.Rectangle pageSize =
       new com.itextpdf.text.Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
   com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize);
   // step 2
   PdfWriter writer = null;
   Graphics2D g2 = null;
   try {
     writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
     // step 3
     document.open();
     // step 4
     PdfContentByte canvas = writer.getDirectContent();
     g2 = canvas.createGraphics(pageSize.getWidth(), pageSize.getHeight());
     trackScheme.getGUI().graphComponent.getViewport().paintComponents(g2);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (DocumentException e) {
     e.printStackTrace();
   } finally {
     g2.dispose();
     document.close();
   }
 }
 public void onEndPage(PdfWriter writer, Document document) {
   Rectangle rect = writer.getBoxSize("art");
   // ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, new
   // Phrase(grupo), rect.getRight(), rect.getBottom(), 0);
   ColumnText.showTextAligned(
       writer.getDirectContent(),
       Element.ALIGN_CENTER,
       new Phrase("Pagina " + pages),
       rect.getLeft(),
       rect.getBottom(),
       0);
 }
Пример #8
0
 public void addColumn(PdfWriter writer, Rectangle rect, boolean useAscender)
     throws DocumentException {
   rect.setBorder(Rectangle.BOX);
   rect.setBorderWidth(0.5f);
   rect.setBorderColor(BaseColor.RED);
   PdfContentByte cb = writer.getDirectContent();
   cb.rectangle(rect);
   Phrase p = new Phrase("This text is added at the top of the column.");
   ColumnText ct = new ColumnText(cb);
   ct.setSimpleColumn(rect);
   ct.setUseAscender(useAscender);
   ct.addText(p);
   ct.go();
 }
Пример #9
0
 /**
  * Main method.
  *
  * @param args no arguments needed
  * @throws DocumentException
  * @throws IOException
  */
 public static void main(String[] args) throws IOException, DocumentException {
   // step 1
   Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30);
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
   // step 3
   document.open();
   // step 4
   // Create and add a Paragraph
   Paragraph p = new Paragraph("Foobar Film Festival", new Font(FontFamily.HELVETICA, 22));
   p.setAlignment(Element.ALIGN_CENTER);
   document.add(p);
   // Create and add an Image
   Image img = Image.getInstance(RESOURCE);
   img.setAbsolutePosition(
       (PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
       (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
   document.add(img);
   // Now we go to the next page
   document.newPage();
   document.add(p);
   document.add(img);
   // Add text on top of the image
   PdfContentByte over = writer.getDirectContent();
   over.saveState();
   float sinus = (float) Math.sin(Math.PI / 60);
   float cosinus = (float) Math.cos(Math.PI / 60);
   BaseFont bf = BaseFont.createFont();
   over.beginText();
   over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
   over.setLineWidth(1.5f);
   over.setRGBColorStroke(0xFF, 0x00, 0x00);
   over.setRGBColorFill(0xFF, 0xFF, 0xFF);
   over.setFontAndSize(bf, 36);
   over.setTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
   over.showText("SOLD OUT");
   over.endText();
   over.restoreState();
   // Add a rectangle under the image
   PdfContentByte under = writer.getDirectContentUnder();
   under.saveState();
   under.setRGBColorFill(0xFF, 0xD7, 0x00);
   under.rectangle(5, 5, PageSize.POSTCARD.getWidth() - 10, PageSize.POSTCARD.getHeight() - 10);
   under.fill();
   under.restoreState();
   // step 4
   document.close();
 }
Пример #10
0
 /**
  * Creates a PDF document.
  *
  * @param filename the path to the new PDF document
  * @param locale Locale in case you want to create a Calendar in another language
  * @param year the year for which you want to make a calendar
  * @throws DocumentException
  * @throws IOException
  */
 public void createPdf(String filename, Locale locale, int year)
     throws IOException, DocumentException {
   // step 1
   Document document = new Document(PageSize.A4.rotate());
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
   // step 3
   document.open();
   // step 4
   PdfPTable table;
   Calendar calendar;
   PdfContentByte canvas = writer.getDirectContent();
   // Loop over the months
   for (int month = 0; month < 12; month++) {
     calendar = new GregorianCalendar(year, month, 1);
     // draw the background
     drawImageAndText(canvas, calendar);
     // create a table with 7 columns
     table = new PdfPTable(7);
     table.setTableEvent(tableBackground);
     table.setTotalWidth(504);
     // add the name of the month
     table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
     table.getDefaultCell().setCellEvent(whiteRectangle);
     table.addCell(getMonthCell(calendar, locale));
     int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
     int day = 1;
     int position = 2;
     // add empty cells
     while (position != calendar.get(Calendar.DAY_OF_WEEK)) {
       position = (position % 7) + 1;
       table.addCell("");
     }
     // add cells for each day
     while (day <= daysInMonth) {
       calendar = new GregorianCalendar(year, month, day++);
       table.addCell(getDayCell(calendar, locale));
     }
     // complete the table
     table.completeRow();
     // write the table to an absolute position
     table.writeSelectedRows(0, -1, 169, table.getTotalHeight() + 20, canvas);
     document.newPage();
   }
   // step 5
   document.close();
 }
Пример #11
0
  /**
   * Constructor. Takes in a string representing where the file should be written to disk.
   *
   * @param fname
   * @throws DocumentException
   * @throws FileNotFoundException
   */
  public BarcodePdf(String fname) throws FileNotFoundException, DocumentException {

    _d = new Document();

    _writer = PdfWriter.getInstance(_d, new FileOutputStream(fname));

    _d.setMargins(25, 25, 25, 25);
    _d.open();

    _open = true;
    _rawContent = _writer.getDirectContent();

    _table = new PdfPTable(4);
    _table.setHorizontalAlignment(Element.ALIGN_CENTER);

    _itemsAdded = 0;
  }
Пример #12
0
 /**
  * Creates a PDF document.
  *
  * @param filename the path to the new PDF document
  * @throws DocumentException
  * @throws IOException
  * @throws BadLocationException
  */
 public void createPdf(String filename)
     throws IOException, DocumentException, BadLocationException {
   Document document = new Document(new Rectangle(300, 150));
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
   document.open();
   PdfContentByte canvas = writer.getDirectContent();
   DefaultFontMapper mapper = new DefaultFontMapper();
   BaseFontParameters parameters = new BaseFontParameters("c:/windows/fonts/msgothic.ttc,1");
   parameters.encoding = BaseFont.IDENTITY_H;
   mapper.putName("MS PGothic", parameters);
   Graphics2D g2 = canvas.createGraphics(300, 150, mapper);
   JTextPane text = TextExample4.createTextPane();
   text.setSize(new Dimension(300, 150));
   text.print(g2);
   g2.dispose();
   document.close();
 }
Пример #13
0
  private static Image getBarcode(Document document, PdfWriter pdfWriter, String servicio) {

    PdfContentByte cimg = pdfWriter.getDirectContent();
    Barcode128 code128 = new Barcode128();
    code128.setCode(servicio);
    code128.setCodeType(Barcode128.CODE128);
    code128.setTextAlignment(Element.ALIGN_CENTER);
    Image image = code128.createImageWithBarcode(cimg, null, null);
    float scaler = (5);
    image.scalePercent(scaler);
    image.setAlignment(Element.ALIGN_CENTER);
    image.scaleAbsoluteWidth(800);

    System.out.print(" Width: " + image.getWidth());
    System.out.println(" Heights: " + image.getHeight());
    return image;
  }
Пример #14
0
 /**
  * Create a pushbutton for a key
  *
  * @param writer the PdfWriter
  * @param rect the position of the key
  * @param btn the label for the key
  * @param script the script to be executed when the button is pushed
  */
 public void addPushButton(PdfWriter writer, Rectangle rect, String btn, String script) {
   float w = rect.getWidth();
   float h = rect.getHeight();
   PdfFormField pushbutton = PdfFormField.createPushButton(writer);
   pushbutton.setFieldName("btn_" + btn);
   pushbutton.setWidget(rect, PdfAnnotation.HIGHLIGHT_PUSH);
   PdfContentByte cb = writer.getDirectContent();
   pushbutton.setAppearance(
       PdfAnnotation.APPEARANCE_NORMAL, createAppearance(cb, btn, BaseColor.GRAY, w, h));
   pushbutton.setAppearance(
       PdfAnnotation.APPEARANCE_ROLLOVER, createAppearance(cb, btn, BaseColor.RED, w, h));
   pushbutton.setAppearance(
       PdfAnnotation.APPEARANCE_DOWN, createAppearance(cb, btn, BaseColor.BLUE, w, h));
   pushbutton.setAdditionalActions(PdfName.U, PdfAction.javaScript(script, writer));
   pushbutton.setAdditionalActions(
       PdfName.E, PdfAction.javaScript("this.showMove('" + btn + "');", writer));
   pushbutton.setAdditionalActions(PdfName.X, PdfAction.javaScript("this.showMove(' ');", writer));
   writer.addAnnotation(pushbutton);
 }
Пример #15
0
  private void getTransactionHeader(ArrayList<String> docList)
      throws DocumentException, IOException {

    //        Paragraph paragraph = new Paragraph(15, "", new Font(getcalibri(),
    // 11,Font.UNDERLINE));
    //        paragraph.setAlignment(Element.ALIGN_CENTER);
    //        document.add(new Chunk(paragraph, BOLD_UNDERLINED));

    //        paragraph.setAlignment(Element.ALIGN_RIGHT);

    Chunk underline = new Chunk("Document List", new Font(getcalibri(), 11, Font.BOLD));
    underline.setUnderline(0.4f, -2f); // 0.1 thick, -2 y-location

    Paragraph paragraph = new Paragraph(25, underline);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);

    document.add(Chunk.NEWLINE);

    PdfPTable table21 = new PdfPTable(1);
    // table1.setWidths(new int[]{24, 24, 2});
    table21.setTotalWidth(507);
    table21.setLockedWidth(true);
    table21.getDefaultCell().setFixedHeight(20);
    table21.getDefaultCell().setBorder(Rectangle.BOTTOM);
    table21.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);

    Iterator<String> it = docList.iterator();
    int i = 1;
    while (it.hasNext()) {
      PdfPCell secondCell =
          new PdfPCell(
              new Phrase(25, i + ".  " + it.next(), new Font(getcalibri(), 11, Font.NORMAL)));
      secondCell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
      secondCell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      secondCell.setBorder(Rectangle.NO_BORDER);
      secondCell.setPadding(15);
      table21.addCell(secondCell);
      i++;
    }

    table21.writeSelectedRows(0, -1, 34, 700, writer.getDirectContent());
  }
 private static void createCheckbox(
     PdfWriter writer,
     Document accountingDocument,
     Font font,
     String[] label,
     int xPosition,
     int yPosition,
     boolean[] checked,
     int pageNr) {
   PdfContentByte canvas = writer.getDirectContent();
   //    Rectangle rect;
   //    PdfFormField field;
   //    RadioCheckField checkbox;
   try {
     Image checkbox_checked =
         Image.getInstance(MainWindow.class.getResource("checkbox_checked.jpg"));
     checkbox_checked.scaleAbsolute(10f, 10f);
     Image checkbox = Image.getInstance(MainWindow.class.getResource("checkbox.jpg"));
     checkbox.scaleAbsolute(10f, 10f);
     for (int i = 0; i < label.length; i++) {
       Image checkboxImage;
       if (checked[i]) {
         checkboxImage = Image.getInstance(checkbox_checked);
       } else {
         checkboxImage = Image.getInstance(checkbox);
       }
       checkboxImage.setAbsolutePosition(xPosition, (yPosition - 10 - i * 15));
       accountingDocument.add(checkboxImage);
       ColumnText.showTextAligned(
           canvas,
           Element.ALIGN_LEFT,
           new Phrase(label[i], font),
           (xPosition + 16),
           (yPosition - 8 - i * 15),
           0);
     }
     // TODO: for JDK7 use Multicatch
   } catch (Exception e) { // com.itextpdf.text.DocumentException | java.io.IOException e) {
     UtilityBox.getInstance()
         .displayErrorPopup(
             "Abrechnung", "Fehler beim Erstellen der Abrechnung: " + e.getMessage());
   }
 }
Пример #17
0
 public void absText(
     PdfWriter twriter, String text, float ypostex12, float ypostex22, int fontsize) {
   try {
     PdfContentByte cb = twriter.getDirectContent();
     BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
     cb.saveState();
     cb.beginText();
     cb.moveText(ypostex12, ypostex22);
     cb.setFontAndSize(bf, fontsize);
     cb.setColorFill(new BaseColor(0, 0, 0));
     cb.showText(text);
     cb.endText();
     cb.restoreState();
   } catch (DocumentException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 public static void main(String[] args) {
   Document document = new Document(); // 打开文档
   try {
     PdfWriter writer =
         PdfWriter.getInstance(
             document, new FileOutputStream("c:\\使用PdfGraphics2D绘制图片.pdf")); // 关联文档与输出流
     document.open(); // 打开文档
     PdfContentByte cb = writer.getDirectContent(); // 获取文档内容
     PdfGraphics2D g = (PdfGraphics2D) cb.createGraphics(700, 800); // 创建PdfGraphics2D对象
     BufferedImage image = ImageIO.read(new File("image/picture.jpg")); // 获取图片
     g.drawImage(image, 50, 10, null); // 绘制图片
     g.dispose(); // 部署
     cb.stroke(); // 确认绘制的内容
     document.close(); // 关闭文档
   } catch (IOException e) {
     e.printStackTrace();
   } catch (DocumentException e) {
     e.printStackTrace();
   }
 }
Пример #19
0
  public static void buildPdf(PrinterJob job, OutputStream os) throws DocumentException {
    Document doc = new Document(getPageSizeFromPaper(job.getPaper()));
    PdfWriter pdfWriter = PdfWriter.getInstance(doc, os);
    doc.open();

    for (int i = 0; job.getNumberOfPages() < 0 || i < job.getNumberOfPages(); i++) {

      if (job.getNumberOfPages() < 0) {
        if (!job.render(DUMMYRENDERSPACE, i)) {
          break;
        }
      }

      PdfContentByte cb = pdfWriter.getDirectContent();
      PdfTemplate pdfTemplate =
          cb.createTemplate(doc.getPageSize().getWidth(), doc.getPageSize().getHeight());
      Graphics2D g2d =
          pdfTemplate.createGraphics(
              doc.getPageSize().getWidth(), doc.getPageSize().getHeight(), new DefaultFontMapper());
      try {
        if (job.render(g2d, i)) {
          g2d.dispose();
          if (i > 0) {
            doc.newPage();
          }
          cb.addTemplate(pdfTemplate, 0, 0);
        } else {
          throw new PrinterException("Unknow error occured.");
        }
      } catch (PrinterException ex) {
        break;
      } finally {

      }
    }
    doc.close();
  }
Пример #20
0
  public void createPdf(String dest) throws IOException, DocumentException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    // step 3
    document.open();
    // step 4
    PdfContentByte canvas = writer.getDirectContent();
    PdfShading axial =
        PdfShading.simpleAxial(writer, 36, 716, 396, 788, BaseColor.ORANGE, BaseColor.BLUE);
    canvas.paintShading(axial);
    document.newPage();
    PdfShading radial =
        PdfShading.simpleRadial(
            writer,
            200,
            700,
            50,
            300,
            700,
            100,
            new BaseColor(0xFF, 0xF7, 0x94),
            new BaseColor(0xF7, 0x8A, 0x6B),
            false,
            false);
    canvas.paintShading(radial);

    PdfShadingPattern shading = new PdfShadingPattern(axial);
    colorRectangle(canvas, new ShadingColor(shading), 150, 420, 126, 126);
    canvas.setShadingFill(shading);
    canvas.rectangle(300, 420, 126, 126);
    canvas.fillStroke();
    // step 5
    document.close();
  }
Пример #21
0
  @Override
  // initialization of the header table
  public void onEndPage(final PdfWriter writer, final Document document) {
    final PdfPTable header = new PdfPTable(2);
    final Phrase p = new Phrase();
    final Chunk ck = new Chunk(_challengeTitle + "\n" + _reportTitle, _font);
    p.add(ck);
    header.getDefaultCell().setBorderWidth(0);
    header.addCell(p);
    header.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_RIGHT);
    header.addCell(
        new Phrase(new Chunk("Tournament: " + _tournament + "\nDate: " + _formattedDate, _font)));
    final PdfPCell blankCell = new PdfPCell();
    blankCell.setBorder(0);
    blankCell.setBorderWidthTop(1.0f);
    blankCell.setColspan(2);
    header.addCell(blankCell);

    final PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    header.setTotalWidth(document.right() - document.left());
    header.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 10, cb);
    cb.restoreState();
  }
Пример #22
0
 @Override
 public void performPrint(IItem item, Document document, PdfWriter writer) throws ReportException {
   PageSize pageSize = pageSizePreference.getPageSize();
   ICharacter stattedCharacter = (ICharacter) item.getItemData();
   PdfContentByte directContent = writer.getDirectContent();
   PageConfiguration configuration = PageConfiguration.ForPortrait(pageSize);
   SheetGraphics graphics = SheetGraphics.WithHelvetica(directContent);
   try {
     IGenericCharacter character =
         GenericCharacterUtilities.createGenericCharacter(stattedCharacter);
     ReportSession session = new ReportSession(getContentRegistry(), character);
     List<PageEncoder> encoderList = new ArrayList<>();
     encoderList.add(new ExtendedFirstPageEncoder(configuration));
     encoderList.add(new ExtendedSecondPageEncoder(configuration));
     Collections.addAll(encoderList, findAdditionalPages(pageSize, session));
     encoderList.add(new ExtendedMagicPageEncoder(getEncoderRegistry(), configuration));
     Sheet sheet = new Sheet(document, getEncoderRegistry(), resources, pageSize);
     for (PageEncoder encoder : encoderList) {
       encoder.encode(sheet, graphics, session);
     }
   } catch (Exception e) {
     throw new ReportException(e);
   }
 }
 /**
  * Creates a PDF document.
  *
  * @param filename the path to the new PDF document
  * @throws DocumentException
  * @throws IOException
  */
 public void createPdf(String filename) throws IOException, DocumentException {
   // step 1
   Document document = new Document(PageSize.A4.rotate());
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
   // step 3
   document.open();
   // step 4
   PdfContentByte over = writer.getDirectContent();
   PdfContentByte under = writer.getDirectContentUnder();
   try {
     DatabaseConnection connection = new HsqldbConnection("filmfestival");
     locations = PojoFactory.getLocations(connection);
     List<Date> days = PojoFactory.getDays(connection);
     List<Screening> screenings;
     int d = 1;
     for (Date day : days) {
       drawTimeTable(under);
       drawTimeSlots(over);
       drawInfo(over);
       drawDateInfo(day, d++, over);
       screenings = PojoFactory.getScreenings(connection, day);
       for (Screening screening : screenings) {
         drawBlock(screening, under, over);
         drawMovieInfo(screening, over);
       }
       document.newPage();
     }
     connection.close();
   } catch (SQLException sqle) {
     sqle.printStackTrace();
     document.add(new Paragraph("Database error: " + sqle.getMessage()));
   }
   // step 5
   document.close();
 }
Пример #24
0
  private static void addScrambles(
      PdfWriter docWriter, Document doc, ScrambleRequest scrambleRequest, String globalTitle)
      throws DocumentException, IOException {
    if (scrambleRequest.fmc) {
      Rectangle pageSize = doc.getPageSize();
      for (int i = 0; i < scrambleRequest.scrambles.length; i++) {
        String scramble = scrambleRequest.scrambles[i];
        PdfContentByte cb = docWriter.getDirectContent();
        float LINE_THICKNESS = 0.5f;
        BaseFont bf =
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

        int bottom = 30;
        int left = 35;
        int right = (int) (pageSize.getWidth() - left);
        int top = (int) (pageSize.getHeight() - bottom);

        int height = top - bottom;
        int width = right - left;

        int solutionBorderTop = bottom + (int) (height * .5);
        int scrambleBorderTop = solutionBorderTop + 40;

        int competitorInfoBottom = top - (int) (height * .15);
        int gradeBottom = competitorInfoBottom - 50;
        int competitorInfoLeft = right - (int) (width * .45);

        int rulesRight = competitorInfoLeft;

        int padding = 5;

        // Outer border
        cb.setLineWidth(2f);
        cb.moveTo(left, top);
        cb.lineTo(left, bottom);
        cb.lineTo(right, bottom);
        cb.lineTo(right, top);

        // Solution border
        cb.moveTo(left, solutionBorderTop);
        cb.lineTo(right, solutionBorderTop);

        // Rules bottom border
        cb.moveTo(left, scrambleBorderTop);
        cb.lineTo(rulesRight, scrambleBorderTop);

        // Rules right border
        cb.lineTo(rulesRight, gradeBottom);

        // Grade bottom border
        cb.moveTo(competitorInfoLeft, gradeBottom);
        cb.lineTo(right, gradeBottom);

        // Competitor info bottom border
        cb.moveTo(competitorInfoLeft, competitorInfoBottom);
        cb.lineTo(right, competitorInfoBottom);

        // Competitor info left border
        cb.moveTo(competitorInfoLeft, gradeBottom);
        cb.lineTo(competitorInfoLeft, top);

        // Solution lines
        int availableSolutionWidth = right - left;
        int availableSolutionHeight = scrambleBorderTop - bottom;
        int lineWidth = 25;
        // int linesX = (availableSolutionWidth/lineWidth + 1)/2;
        int linesX = 10;
        int linesY = (int) Math.ceil(1.0 * WCA_MAX_MOVES_FMC / linesX);

        cb.setLineWidth(LINE_THICKNESS);
        cb.stroke();

        //              int allocatedX = (2*linesX-1)*lineWidth;
        int excessX = availableSolutionWidth - linesX * lineWidth;
        int moveCount = 0;
        solutionLines:
        for (int y = 0; y < linesY; y++) {
          for (int x = 0; x < linesX; x++) {
            if (moveCount >= WCA_MAX_MOVES_FMC) {
              break solutionLines;
            }
            int xPos = left + x * lineWidth + (x + 1) * excessX / (linesX + 1);
            int yPos = solutionBorderTop - (y + 1) * availableSolutionHeight / (linesY + 1);
            cb.moveTo(xPos, yPos);
            cb.lineTo(xPos + lineWidth, yPos);
            moveCount++;
          }
        }

        float UNDERLINE_THICKNESS = 0.2f;
        cb.setLineWidth(UNDERLINE_THICKNESS);
        cb.stroke();

        cb.beginText();
        int availableScrambleSpace = right - left - 2 * padding;
        int scrambleFontSize = 20;
        String scrambleStr = "Scramble: " + scramble;
        float scrambleWidth;
        do {
          scrambleFontSize--;
          scrambleWidth = bf.getWidthPoint(scrambleStr, scrambleFontSize);
        } while (scrambleWidth > availableScrambleSpace);

        cb.setFontAndSize(bf, scrambleFontSize);
        int scrambleY =
            3 + solutionBorderTop + (scrambleBorderTop - solutionBorderTop - scrambleFontSize) / 2;
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, scrambleStr, left + padding, scrambleY, 0);
        cb.endText();

        int availableScrambleWidth = right - rulesRight;
        int availableScrambleHeight = gradeBottom - scrambleBorderTop;
        Dimension dim =
            scrambleRequest.scrambler.getPreferredSize(
                availableScrambleWidth - 2, availableScrambleHeight - 2);
        PdfTemplate tp = cb.createTemplate(dim.width, dim.height);
        Graphics2D g2 = new PdfGraphics2D(tp, dim.width, dim.height, new DefaultFontMapper());

        try {
          Svg svg = scrambleRequest.scrambler.drawScramble(scramble, scrambleRequest.colorScheme);
          drawSvgToGraphics2D(svg, g2, dim);
        } catch (InvalidScrambleException e) {
          l.log(Level.INFO, "", e);
        } finally {
          g2.dispose();
        }

        cb.addImage(
            Image.getInstance(tp),
            dim.width,
            0,
            0,
            dim.height,
            rulesRight + (availableScrambleWidth - dim.width) / 2,
            scrambleBorderTop + (availableScrambleHeight - dim.height) / 2);

        ColumnText ct = new ColumnText(cb);

        int fontSize = 15;
        int marginBottom = 10;
        int offsetTop = 27;
        boolean showScrambleCount = scrambleRequest.scrambles.length > 1;
        if (showScrambleCount) {
          offsetTop -= fontSize + 2;
        }

        cb.beginText();
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            globalTitle,
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        offsetTop += fontSize + 2;
        cb.endText();

        cb.beginText();
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            scrambleRequest.title,
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        cb.endText();

        if (showScrambleCount) {
          cb.beginText();
          offsetTop += fontSize + 2;
          cb.setFontAndSize(bf, fontSize);
          cb.showTextAligned(
              PdfContentByte.ALIGN_CENTER,
              "Scramble " + (i + 1) + " of " + scrambleRequest.scrambles.length,
              competitorInfoLeft + (right - competitorInfoLeft) / 2,
              top - offsetTop,
              0);
          cb.endText();
        }

        offsetTop += fontSize + marginBottom;

        cb.beginText();
        fontSize = 15;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_LEFT,
            "Competitor: __________________",
            competitorInfoLeft + padding,
            top - offsetTop,
            0);
        offsetTop += fontSize + marginBottom;
        cb.endText();

        cb.beginText();

        fontSize = 15;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_LEFT, "WCA ID:", competitorInfoLeft + padding, top - offsetTop, 0);

        cb.setFontAndSize(bf, 19);
        int wcaIdLength = 63;
        cb.showTextAligned(
            PdfContentByte.ALIGN_LEFT,
            "_ _ _ _  _ _ _ _  _ _",
            competitorInfoLeft + padding + wcaIdLength,
            top - offsetTop,
            0);

        offsetTop += fontSize + (int) (marginBottom * 1.8);
        cb.endText();

        cb.beginText();
        fontSize = 11;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            "DO NOT FILL IF YOU ARE THE COMPETITOR",
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        offsetTop += fontSize + marginBottom;
        cb.endText();

        cb.beginText();
        fontSize = 11;
        cb.setFontAndSize(bf, fontSize);
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            "Graded by: _______________ Result: ______",
            competitorInfoLeft + (right - competitorInfoLeft) / 2,
            top - offsetTop,
            0);
        offsetTop += fontSize + marginBottom;
        cb.endText();

        cb.beginText();
        cb.setFontAndSize(bf, 25f);
        int MAGIC_NUMBER = 40; // kill me now
        cb.showTextAligned(
            PdfContentByte.ALIGN_CENTER,
            "Fewest Moves",
            left + (competitorInfoLeft - left) / 2,
            top - MAGIC_NUMBER,
            0);
        cb.endText();

        com.itextpdf.text.List rules = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        rules.add("Notate your solution by writing one move per bar.");
        rules.add("To delete moves, clearly erase/blacken them.");
        rules.add("Face moves F, B, R, L, U, and D are clockwise.");
        rules.add("Rotations x, y, and z follow R, U, and F.");
        rules.add("' inverts a move; 2 doubles a move. (e.g.: U', U2)");
        rules.add("w makes a face move into two layers. (e.g.: Uw)");
        rules.add("A [lowercase] move is a cube rotation. (e.g.: [u])");

        ct.addElement(rules);
        int rulesTop = competitorInfoBottom + 55;
        ct.setSimpleColumn(
            left + padding,
            scrambleBorderTop,
            competitorInfoLeft - padding,
            rulesTop,
            0,
            Element.ALIGN_LEFT);
        ct.go();

        rules = new com.itextpdf.text.List(com.itextpdf.text.List.UNORDERED);
        rules.add("You have 1 hour to find a solution.");
        rules.add("Your solution length will be counted in OBTM.");
        int maxMoves = WCA_MAX_MOVES_FMC;
        rules.add("Your solution must be at most " + maxMoves + " moves, including rotations.");
        rules.add(
            "Your solution must not be directly derived from any part of the scrambling algorithm.");
        ct.addElement(rules);
        MAGIC_NUMBER = 150; // kill me now
        ct.setSimpleColumn(
            left + padding,
            scrambleBorderTop,
            rulesRight - padding,
            rulesTop - MAGIC_NUMBER,
            0,
            Element.ALIGN_LEFT);
        ct.go();

        doc.newPage();
      }
    } else {
      Rectangle pageSize = doc.getPageSize();

      float sideMargins = 100 + doc.leftMargin() + doc.rightMargin();
      float availableWidth = pageSize.getWidth() - sideMargins;
      float vertMargins = doc.topMargin() + doc.bottomMargin();
      float availableHeight = pageSize.getHeight() - vertMargins;
      if (scrambleRequest.extraScrambles.length > 0) {
        availableHeight -= 20; // Yeee magic numbers. This should make space for the headerTable.
      }
      int scramblesPerPage =
          Math.min(MAX_SCRAMBLES_PER_PAGE, scrambleRequest.getAllScrambles().size());
      int maxScrambleImageHeight =
          (int) (availableHeight / scramblesPerPage - 2 * SCRAMBLE_IMAGE_PADDING);

      int maxScrambleImageWidth =
          (int)
              (availableWidth / 2); // We don't let scramble images take up more than half the page
      if (scrambleRequest.scrambler.getShortName().equals("minx")) {
        // TODO - If we allow the megaminx image to be too wide, the
        // megaminx scrambles get really tiny. This tweak allocates
        // a more optimal amount of space to the scrambles. This is possible
        // because the scrambles are so uniformly sized.
        maxScrambleImageWidth = 190;
      }

      Dimension scrambleImageSize =
          scrambleRequest.scrambler.getPreferredSize(maxScrambleImageWidth, maxScrambleImageHeight);

      // First do a dry run just to see if any scrambles require highlighting.
      // Then do the real run, and force highlighting on every scramble
      // if any scramble required it.
      boolean forceHighlighting = false;
      for (boolean dryRun : new boolean[] {true, false}) {
        String scrambleNumberPrefix = "";
        TableAndHighlighting tableAndHighlighting =
            createTable(
                docWriter,
                doc,
                sideMargins,
                scrambleImageSize,
                scrambleRequest.scrambles,
                scrambleRequest.scrambler,
                scrambleRequest.colorScheme,
                scrambleNumberPrefix,
                forceHighlighting);
        if (dryRun) {
          if (tableAndHighlighting.highlighting) {
            forceHighlighting = true;
            continue;
          }
        } else {
          doc.add(tableAndHighlighting.table);
        }

        if (scrambleRequest.extraScrambles.length > 0) {
          PdfPTable headerTable = new PdfPTable(1);
          headerTable.setTotalWidth(new float[] {availableWidth});
          headerTable.setLockedWidth(true);

          PdfPCell extraScramblesHeader = new PdfPCell(new Paragraph("Extra scrambles"));
          extraScramblesHeader.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
          extraScramblesHeader.setPaddingBottom(3);
          headerTable.addCell(extraScramblesHeader);
          if (!dryRun) {
            doc.add(headerTable);
          }

          scrambleNumberPrefix = "E";
          TableAndHighlighting extraTableAndHighlighting =
              createTable(
                  docWriter,
                  doc,
                  sideMargins,
                  scrambleImageSize,
                  scrambleRequest.extraScrambles,
                  scrambleRequest.scrambler,
                  scrambleRequest.colorScheme,
                  scrambleNumberPrefix,
                  forceHighlighting);
          if (dryRun) {
            if (tableAndHighlighting.highlighting) {
              forceHighlighting = true;
              continue;
            }
          } else {
            doc.add(extraTableAndHighlighting.table);
          }
        }
      }
    }
    doc.newPage();
  }
  protected void printPatientCard(AdminPerson person) {
    try {
      table = new PdfPTable(1000);
      table.setWidthPercentage(100);
      PdfPTable table2 = new PdfPTable(1000);
      table.setWidthPercentage(100);

      // Professional card
      cell = createLabel(" ", 32, 1, Font.BOLD);
      cell.setColspan(1000);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
      cell.setPadding(0);
      table2.addCell(cell);

      cell = new PdfPCell(table2);
      cell.setColspan(1000);
      cell.setBorder(PdfPCell.NO_BORDER);
      table.addCell(cell);
      cell = createValueCell(" ");
      cell.setColspan(1000);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(0);
      table.addCell(cell);

      table2 = new PdfPTable(1000);
      // Name
      cell =
          createLabel(
              ScreenHelper.getTranNoLink("web", "lastname", sPrintLanguage) + ":",
              6,
              1,
              Font.ITALIC);
      cell.setColspan(300);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(1);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      table2.addCell(cell);
      cell = createLabel(person.lastname, 8, 1, Font.BOLD);
      cell.setColspan(700);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(1);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      table2.addCell(cell);

      // FirstName
      cell =
          createLabel(
              ScreenHelper.getTranNoLink("web", "firstname", sPrintLanguage) + ":",
              6,
              1,
              Font.ITALIC);
      cell.setColspan(300);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(1);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      table2.addCell(cell);
      cell = createLabel(person.firstname, 8, 1, Font.BOLD);
      cell.setColspan(700);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(1);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      table2.addCell(cell);

      // Date of birth
      cell =
          createLabel(
              ScreenHelper.getTranNoLink("web", "dateofbirth", sPrintLanguage) + ":",
              6,
              1,
              Font.ITALIC);
      cell.setColspan(300);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(1);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      table2.addCell(cell);
      cell = createLabel(person.dateOfBirth, 8, 1, Font.BOLD);
      cell.setColspan(700);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(1);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      table2.addCell(cell);

      // Registration number
      cell =
          createLabel(
              ScreenHelper.getTranNoLink("web", "idcode", sPrintLanguage) + ":", 6, 1, Font.ITALIC);
      cell.setColspan(300);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      cell.setPadding(1);
      table2.addCell(cell);
      cell = createLabel(person.comment, 8, 1, Font.BOLD);
      cell.setColspan(700);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPadding(1);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      table2.addCell(cell);

      // Barcode
      PdfContentByte cb = docWriter.getDirectContent();
      Barcode39 barcode39 = new Barcode39();
      barcode39.setCode("A" + person.comment);
      barcode39.setAltText("");
      barcode39.setSize(1);
      barcode39.setBaseline(0);
      barcode39.setBarHeight(20);
      Image image = barcode39.createImageWithBarcode(cb, null, null);
      cell = new PdfPCell(image);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      cell.setColspan(1000);
      cell.setPadding(0);
      table2.addCell(cell);

      cell = new PdfPCell(table2);
      cell.setColspan(700);
      cell.setBorder(PdfPCell.NO_BORDER);
      table.addCell(cell);

      // Photo
      image = null;
      try {
        image = Image.getInstance(DatacenterHelper.getPatientPicture(person.comment));
      } catch (Exception e1) {
        e1.printStackTrace();
      }
      if (image != null) {
        image.scaleToFit(130, 72);
        cell = new PdfPCell(image);
      } else {
        cell = new PdfPCell();
      }
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
      cell.setColspan(300);
      cell.setPadding(0);
      table.addCell(cell);

      // Horizontal line
      cell = new PdfPCell();
      cell.setBorder(PdfPCell.BOTTOM);
      cell.setColspan(1000);
      table.addCell(cell);

      table2 = new PdfPTable(2000);
      cell =
          createLabel(
              ScreenHelper.getTranNoLink("web", "deliverydate", sPrintLanguage), 6, 1, Font.ITALIC);
      cell.setColspan(550);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPaddingRight(5);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
      table2.addCell(cell);
      cell = createLabel(ScreenHelper.stdDateFormat.format(new java.util.Date()), 6, 1, Font.BOLD);
      cell.setColspan(450);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      cell.setPadding(0);
      table2.addCell(cell);

      // Expiry data
      cell =
          createLabel(
              ScreenHelper.getTranNoLink("web", "expirydate", sPrintLanguage), 6, 1, Font.ITALIC);
      cell.setColspan(550);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setPaddingRight(5);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
      table2.addCell(cell);
      long day = 24 * 3600 * 1000;
      long year = 365 * day;
      long period = MedwanQuery.getInstance().getConfigInt("cardvalidityperiod", 5) * year - day;
      cell =
          createLabel(
              ScreenHelper.stdDateFormat.format(
                  new java.util.Date(new java.util.Date().getTime() + period)),
              6,
              1,
              Font.BOLD);
      cell.setColspan(450);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
      cell.setPadding(0);
      table2.addCell(cell);

      cell = new PdfPCell(table2);
      cell.setColspan(1000);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
      cell.setPadding(1);
      table.addCell(cell);

      cell =
          createLabel(
              ScreenHelper.getTranNoLink("web", "cardfooter2", sPrintLanguage), 6, 1, Font.ITALIC);
      cell.setColspan(1000);
      cell.setBorder(PdfPCell.NO_BORDER);
      cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
      cell.setPadding(0);
      table.addCell(cell);

      doc.add(table);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #26
0
  private static TableAndHighlighting createTable(
      PdfWriter docWriter,
      Document doc,
      float sideMargins,
      Dimension scrambleImageSize,
      String[] scrambles,
      Puzzle scrambler,
      HashMap<String, Color> colorScheme,
      String scrambleNumberPrefix,
      boolean forceHighlighting)
      throws DocumentException {
    PdfContentByte cb = docWriter.getDirectContent();

    PdfPTable table = new PdfPTable(3);

    int charsWide = scrambleNumberPrefix.length() + 1 + (int) Math.log10(scrambles.length);
    String wideString = "";
    for (int i = 0; i < charsWide; i++) {
      // M has got to be as wide or wider than the widest digit in our font
      wideString += "M";
    }
    wideString += ".";
    float col1Width = new Chunk(wideString).getWidthPoint();
    // I don't know why we need this, perhaps there's some padding?
    col1Width += 5;

    float availableWidth = doc.getPageSize().getWidth() - sideMargins;
    float scrambleColumnWidth =
        availableWidth - col1Width - scrambleImageSize.width - 2 * SCRAMBLE_IMAGE_PADDING;
    int availableScrambleHeight = scrambleImageSize.height - 2 * SCRAMBLE_IMAGE_PADDING;

    table.setTotalWidth(
        new float[] {
          col1Width, scrambleColumnWidth, scrambleImageSize.width + 2 * SCRAMBLE_IMAGE_PADDING
        });
    table.setLockedWidth(true);

    String longestScramble = "";
    String longestPaddedScramble = "";
    for (String scramble : scrambles) {
      if (scramble.length() > longestScramble.length()) {
        longestScramble = scramble;
      }

      String paddedScramble = padTurnsUniformly(scramble, "M");
      if (paddedScramble.length() > longestPaddedScramble.length()) {
        longestPaddedScramble = paddedScramble;
      }
    }
    // I don't know how to configure ColumnText.fitText's word wrapping characters,
    // so instead, I just replace each character I don't want to wrap with M, which
    // should be the widest character (we're using a monospaced font,
    // so that doesn't really matter), and won't get wrapped.
    char widestCharacter = 'M';
    longestPaddedScramble = longestPaddedScramble.replaceAll("\\S", widestCharacter + "");
    boolean tryToFitOnOneLine = true;
    if (longestPaddedScramble.indexOf("\n") >= 0) {
      // If the scramble contains newlines, then we *only* allow wrapping at the
      // newlines.
      longestPaddedScramble = longestPaddedScramble.replaceAll(" ", "M");
      tryToFitOnOneLine = false;
    }
    boolean oneLine = false;
    Font scrambleFont = null;

    try {
      BaseFont courier = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.EMBEDDED);
      Rectangle availableArea =
          new Rectangle(
              scrambleColumnWidth - 2 * SCRAMBLE_PADDING_HORIZONTAL,
              availableScrambleHeight
                  - SCRAMBLE_PADDING_VERTICAL_TOP
                  - SCRAMBLE_PADDING_VERTICAL_BOTTOM);
      float perfectFontSize =
          fitText(
              new Font(courier),
              longestPaddedScramble,
              availableArea,
              MAX_SCRAMBLE_FONT_SIZE,
              true);
      if (tryToFitOnOneLine) {
        String longestScrambleOneLine = longestScramble.replaceAll(".", widestCharacter + "");
        float perfectFontSizeForOneLine =
            fitText(
                new Font(courier),
                longestScrambleOneLine,
                availableArea,
                MAX_SCRAMBLE_FONT_SIZE,
                false);
        oneLine = perfectFontSizeForOneLine >= MINIMUM_ONE_LINE_FONT_SIZE;
        if (oneLine) {
          perfectFontSize = perfectFontSizeForOneLine;
        }
      }
      scrambleFont = new Font(courier, perfectFontSize, Font.NORMAL);
    } catch (IOException e) {
      l.log(Level.INFO, "", e);
    } catch (DocumentException e) {
      l.log(Level.INFO, "", e);
    }

    boolean highlight = forceHighlighting;
    for (int i = 0; i < scrambles.length; i++) {
      String scramble = scrambles[i];
      String paddedScramble =
          oneLine ? scramble : padTurnsUniformly(scramble, NON_BREAKING_SPACE + "");
      Chunk ch = new Chunk(scrambleNumberPrefix + (i + 1) + ".");
      PdfPCell nthscramble = new PdfPCell(new Paragraph(ch));
      nthscramble.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
      table.addCell(nthscramble);

      Phrase scramblePhrase = new Phrase();
      int nthLine = 1;
      LinkedList<Chunk> lineChunks =
          splitScrambleToLineChunks(paddedScramble, scrambleFont, scrambleColumnWidth);
      if (lineChunks.size() >= MIN_LINES_TO_ALTERNATE_HIGHLIGHTING) {
        highlight = true;
      }

      for (Chunk lineChunk : lineChunks) {
        if (highlight && (nthLine % 2 == 0)) {
          lineChunk.setBackground(HIGHLIGHT_COLOR);
        }
        scramblePhrase.add(lineChunk);
        nthLine++;
      }

      PdfPCell scrambleCell = new PdfPCell(new Paragraph(scramblePhrase));
      // We carefully inserted newlines ourselves to make stuff fit, don't
      // let itextpdf wrap lines for us.
      scrambleCell.setNoWrap(true);
      scrambleCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
      // This shifts everything up a little bit, because I don't like how
      // ALIGN_MIDDLE works.
      scrambleCell.setPaddingTop(-SCRAMBLE_PADDING_VERTICAL_TOP);
      scrambleCell.setPaddingBottom(SCRAMBLE_PADDING_VERTICAL_BOTTOM);
      scrambleCell.setPaddingLeft(SCRAMBLE_PADDING_HORIZONTAL);
      scrambleCell.setPaddingRight(SCRAMBLE_PADDING_HORIZONTAL);
      // We space lines a little bit more here - it still fits in the cell height
      scrambleCell.setLeading(0, 1.1f);
      table.addCell(scrambleCell);

      if (scrambleImageSize.width > 0 && scrambleImageSize.height > 0) {
        PdfTemplate tp =
            cb.createTemplate(
                scrambleImageSize.width + 2 * SCRAMBLE_IMAGE_PADDING,
                scrambleImageSize.height + 2 * SCRAMBLE_IMAGE_PADDING);
        Graphics2D g2 =
            new PdfGraphics2D(tp, tp.getWidth(), tp.getHeight(), new DefaultFontMapper());
        g2.translate(SCRAMBLE_IMAGE_PADDING, SCRAMBLE_IMAGE_PADDING);

        try {
          Svg svg = scrambler.drawScramble(scramble, colorScheme);
          drawSvgToGraphics2D(svg, g2, scrambleImageSize);
        } catch (Exception e) {
          table.addCell("Error drawing scramble: " + e.getMessage());
          l.log(
              Level.WARNING,
              "Error drawing scramble, if you're having font issues, try installing ttf-dejavu.",
              e);
          continue;
        } finally {
          g2.dispose(); // iTextPdf blows up if we do not dispose of this
        }
        PdfPCell imgCell = new PdfPCell(Image.getInstance(tp), true);
        imgCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
        imgCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        imgCell.setHorizontalAlignment(PdfPCell.ALIGN_MIDDLE);
        table.addCell(imgCell);
      } else {
        table.addCell("");
      }
    }

    TableAndHighlighting tableAndHighlighting = new TableAndHighlighting();
    tableAndHighlighting.table = table;
    tableAndHighlighting.highlighting = highlight;
    return tableAndHighlighting;
  }
Пример #27
0
  public static void createPdf2(
      List<Participant> participants,
      boolean exportName,
      boolean exportGroup,
      boolean exportRenseignement,
      OutputStream out)
      throws IOException, DocumentException {
    Document document = new Document(PageSize.A4.rotate());
    // document.setMargins(0,0,0,0);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    float documentTop = document.top();
    float documentBottom = document.bottom();
    float documentHeight = documentTop - documentBottom;
    float left = document.left();
    float right = document.right();
    float width = right - left;

    cb.rectangle(left, documentBottom, width, documentHeight);
    cb.stroke();

    float nameHeightPercent = 0.35f;
    float groupHeightPercent = 0.25f;

    float nameTop = documentTop;
    float nameBottom = nameTop;
    if (exportName) {
      nameBottom = nameTop - (documentHeight * nameHeightPercent);
    }
    float groupeTop = nameBottom;
    float groupeBottom = nameBottom;
    if (exportGroup) {
      groupeBottom = groupeTop - (documentHeight * groupHeightPercent);
    }
    float barcodeTop = groupeBottom;
    float barcodeBottom = documentBottom;

    ColumnText columnText;

    for (Participant participant : participants) {

      float nameFontSize = 65f;
      float groupFontSize = 45f;
      float renseignementFontSize = 35f;

      if (exportName) {
        columnText = new ColumnText(cb);

        columnText.setSimpleColumn(left, nameTop, right, nameBottom);
        // cb.rectangle(left, nameBottom, width, (nameTop - nameBottom));
        // cb.stroke();

        columnText.setExtraParagraphSpace(0f);
        columnText.setAdjustFirstLine(false);
        columnText.setIndent(0);

        String txt = participant.getNom().toUpperCase() + " " + participant.getPrenom();

        float previousPos = columnText.getYLine();
        columnText.setText(null);
        columnText.addElement(createCleanParagraph(txt, nameFontSize, true));
        while (ColumnText.hasMoreText(columnText.go(true))) {
          nameFontSize = nameFontSize - 0.5f;
          columnText.setText(null);
          columnText.addElement(createCleanParagraph(txt, nameFontSize, true));
          columnText.setYLine(previousPos);
        }

        columnText.setText(null);
        columnText.addElement(createCleanParagraph(txt, nameFontSize, true));
        columnText.setYLine(previousPos);
        columnText.go(false);
      }

      if (exportGroup) {
        columnText = new ColumnText(cb);

        columnText.setSimpleColumn(document.left(), groupeTop, document.right(), groupeBottom);
        float groupeHeight = groupeTop - groupeBottom;
        // cb.rectangle(document.left(), groupeTop - groupeHeight, document.right() -
        // document.left(), groupeHeight);
        // cb.stroke();

        columnText.setExtraParagraphSpace(0f);
        columnText.setAdjustFirstLine(false);
        columnText.setIndent(0);
        columnText.setFollowingIndent(0);

        String txt1 = participant.getGroupe();
        String txt2 = exportRenseignement ? participant.getRenseignements() : null;

        float previousPos = columnText.getYLine();
        columnText.setText(null);
        // columnText.addElement(createCleanParagraph(txt1,groupFontSize,true,txt2,renseignementFontSize,false));
        columnText.addElement(createCleanParagraph(txt1, groupFontSize, true));
        columnText.addElement(createCleanParagraph(txt2, renseignementFontSize, false));
        while (ColumnText.hasMoreText(columnText.go(true))) {
          groupFontSize = groupFontSize - 0.5f;
          renseignementFontSize = renseignementFontSize - 0.5f;
          columnText.setText(null);
          // columnText.addElement(createCleanParagraph(txt1,groupFontSize,true,txt2,renseignementFontSize,false));
          columnText.addElement(createCleanParagraph(txt1, groupFontSize, true));
          columnText.addElement(createCleanParagraph(txt2, renseignementFontSize, false));
          columnText.setYLine(previousPos);
        }

        columnText.setText(null);
        // columnText.addElement(createCleanParagraph(txt1,groupFontSize,true,txt2,renseignementFontSize,false));
        columnText.addElement(createCleanParagraph(txt1, groupFontSize, true));
        columnText.addElement(createCleanParagraph(txt2, renseignementFontSize, false));
        columnText.setYLine(previousPos);
        columnText.go(false);
      }

      {
        columnText = new ColumnText(cb);

        barcodeTop = barcodeTop - 12f;
        columnText.setSimpleColumn(left, barcodeTop, right, barcodeBottom);
        float barcodeHeight = barcodeTop - barcodeBottom;
        // cb.rectangle(left, barcodeTop - barcodeHeight, width, barcodeHeight);
        // cb.stroke();

        columnText.setExtraParagraphSpace(0f);
        columnText.setAdjustFirstLine(false);
        columnText.setIndent(0);

        float previousPos = columnText.getYLine();
        columnText.setText(null);
        columnText.addElement(
            createCleanBarcode(cb, participant.getNumero(), width, barcodeHeight));
        columnText.go(false);
      }

      document.newPage();
    }

    document.close();
  }
Пример #28
0
  public static void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Document document = new Document(new Rectangle(340, 842));
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    PdfContentByte cb = writer.getDirectContent();

    String code = "2846510";

    // EAN 13
    document.add(new Paragraph("Barcode EAN.UCC-13"));
    BarcodeEAN codeEAN = new BarcodeEAN();
    /*
    //codeEAN.setCode("4512345678906");
    codeEAN.setCode(code);
    document.add(new Paragraph("default:"));
    document.add(codeEAN.createImageWithBarcode(cb, null, null));
    codeEAN.setGuardBars(false);
    document.add(new Paragraph("without guard bars:"));
    document.add(codeEAN.createImageWithBarcode(cb, null, null));
    codeEAN.setBaseline(-1f);
    codeEAN.setGuardBars(true);
    document.add(new Paragraph("text above:"));
    document.add(codeEAN.createImageWithBarcode(cb, null, null));
    codeEAN.setBaseline(codeEAN.getSize());


    // UPC A
    document.add(new Paragraph("Barcode UCC-12 (UPC-A)"));
    codeEAN.setCodeType(Barcode.UPCA);
    //codeEAN.setCode("785342304749");
    codeEAN.setCode(code);
    document.add(codeEAN.createImageWithBarcode(cb, null, null));


    // EAN 8
    document.add(new Paragraph("Barcode EAN.UCC-8"));
    codeEAN.setCodeType(Barcode.EAN8);
    codeEAN.setBarHeight(codeEAN.getSize() * 1.5f);
    //codeEAN.setCode("34569870");
    codeEAN.setCode(code);
    document.add(codeEAN.createImageWithBarcode(cb, null, null));


    // UPC E
    document.add(new Paragraph("Barcode UPC-E"));
    codeEAN.setCodeType(Barcode.UPCE);
    //codeEAN.setCode("03456781");
    codeEAN.setCode(code);
    document.add(codeEAN.createImageWithBarcode(cb, null, null));
    codeEAN.setBarHeight(codeEAN.getSize() * 3f);


    // EANSUPP
    document.add(new Paragraph("Bookland"));
    document.add(new Paragraph("ISBN 0-321-30474-8"));
    codeEAN.setCodeType(Barcode.EAN13);
    //codeEAN.setCode("9781935182610");
    codeEAN.setCode(code);

    BarcodeEAN codeSUPP = new BarcodeEAN();
    codeSUPP.setCodeType(Barcode.SUPP5);
    //codeSUPP.setCode("55999");
    codeSUPP.setCode(code);
    codeSUPP.setBaseline(-2);
    BarcodeEANSUPP eanSupp = new BarcodeEANSUPP(codeEAN, codeSUPP);
    document.add(eanSupp.createImageWithBarcode(cb, null, BaseColor.BLUE));
    */

    // CODE 128
    document.add(new Paragraph("Barcode 128"));
    Barcode128 code128 = new Barcode128();
    // code128.setCode("0123456789 hello");
    code128.setCode(code);
    document.add(code128.createImageWithBarcode(cb, null, null));
    code128.setCode("0123456789\uffffMy Raw Barcode (0 - 9)");
    code128.setCodeType(Barcode.CODE128_RAW);
    document.add(code128.createImageWithBarcode(cb, null, null));

    // Data for the barcode :
    String code402 = "24132399420058289";
    String code90 = "3700000050";
    String code421 = "422356";
    StringBuffer data = new StringBuffer(code402);
    data.append(Barcode128.FNC1);
    data.append(code90);
    data.append(Barcode128.FNC1);
    data.append(code421);
    Barcode128 shipBarCode = new Barcode128();
    shipBarCode.setX(0.75f);
    shipBarCode.setN(1.5f);
    shipBarCode.setSize(10f);
    shipBarCode.setTextAlignment(Element.ALIGN_CENTER);
    shipBarCode.setBaseline(10f);
    shipBarCode.setBarHeight(50f);
    shipBarCode.setCode(data.toString());
    document.add(shipBarCode.createImageWithBarcode(cb, BaseColor.BLACK, BaseColor.BLUE));

    // it is composed of 3 blocks whith AI 01, 3101 and 10
    Barcode128 uccEan128 = new Barcode128();
    uccEan128.setCodeType(Barcode.CODE128_UCC);
    uccEan128.setCode("(01)00000090311314(10)ABC123(15)060916");
    document.add(uccEan128.createImageWithBarcode(cb, BaseColor.BLUE, BaseColor.BLACK));
    uccEan128.setCode("0191234567890121310100035510ABC123");
    document.add(uccEan128.createImageWithBarcode(cb, BaseColor.BLUE, BaseColor.RED));
    uccEan128.setCode("(01)28880123456788");
    document.add(uccEan128.createImageWithBarcode(cb, BaseColor.BLUE, BaseColor.BLACK));

    // INTER25
    document.add(new Paragraph("Barcode Interleaved 2 of 5"));
    BarcodeInter25 code25 = new BarcodeInter25();
    code25.setGenerateChecksum(true);
    code25.setCode("41-1200076041-001");
    document.add(code25.createImageWithBarcode(cb, null, null));
    code25.setCode("411200076041001");
    document.add(code25.createImageWithBarcode(cb, null, null));
    code25.setCode("0611012345678");
    code25.setChecksumText(true);
    document.add(code25.createImageWithBarcode(cb, null, null));

    // POSTNET
    document.add(new Paragraph("Barcode Postnet"));
    BarcodePostnet codePost = new BarcodePostnet();
    document.add(new Paragraph("ZIP"));
    codePost.setCode("01234");
    document.add(codePost.createImageWithBarcode(cb, null, null));
    document.add(new Paragraph("ZIP+4"));
    codePost.setCode("012345678");
    document.add(codePost.createImageWithBarcode(cb, null, null));
    document.add(new Paragraph("ZIP+4 and dp"));
    codePost.setCode("01234567890");
    document.add(codePost.createImageWithBarcode(cb, null, null));

    document.add(new Paragraph("Barcode Planet"));
    BarcodePostnet codePlanet = new BarcodePostnet();
    codePlanet.setCode("01234567890");
    codePlanet.setCodeType(Barcode.PLANET);
    document.add(codePlanet.createImageWithBarcode(cb, null, null));

    // CODE 39
    document.add(new Paragraph("Barcode 3 of 9"));
    Barcode39 code39 = new Barcode39();
    code39.setCode("ITEXT IN ACTION");
    document.add(code39.createImageWithBarcode(cb, null, null));

    document.add(new Paragraph("Barcode 3 of 9 extended"));
    Barcode39 code39ext = new Barcode39();
    code39ext.setCode("iText in Action");
    code39ext.setStartStopText(false);
    code39ext.setExtended(true);
    document.add(code39ext.createImageWithBarcode(cb, null, null));

    // CODABAR
    document.add(new Paragraph("Codabar"));
    BarcodeCodabar codabar = new BarcodeCodabar();
    codabar.setCode("A123A");
    codabar.setStartStopText(true);
    document.add(codabar.createImageWithBarcode(cb, null, null));

    // PDF417
    document.add(new Paragraph("Barcode PDF417"));
    BarcodePDF417 pdf417 = new BarcodePDF417();
    String text =
        "Call me Ishmael. Some years ago--never mind how long "
            + "precisely --having little or no money in my purse, and nothing "
            + "particular to interest me on shore, I thought I would sail about "
            + "a little and see the watery part of the world.";
    pdf417.setText(text);
    Image img = pdf417.getImage();
    img.scalePercent(50, 50 * pdf417.getYHeight());
    document.add(img);

    document.add(new Paragraph("Barcode Datamatrix"));
    BarcodeDatamatrix datamatrix = new BarcodeDatamatrix();
    datamatrix.generate(text);
    img = datamatrix.createImage();
    document.add(img);

    document.add(new Paragraph("Barcode QRCode"));
    BarcodeQRCode qrcode = new BarcodeQRCode("Moby Dick by Herman Melville", 1, 1, null);
    img = qrcode.getImage();
    document.add(img);

    // step 5
    document.close();
  }
Пример #29
0
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
      Rectangle rect = writer.getBoxSize("art");

      Image imghead = null;
      PdfContentByte cbhead = null;

      try {
        imghead = Image.getInstance("LogoSapito5.png");
        imghead.setAbsolutePosition(0, 0);
        imghead.setAlignment(Image.ALIGN_CENTER);
        imghead.scalePercent(10f);
        cbhead = writer.getDirectContent();
        PdfTemplate tp = cbhead.createTemplate(100, 150);
        tp.addImage(imghead);
        cbhead.addTemplate(tp, 100, 715);

      } catch (BadElementException e) {
        e.printStackTrace();
      } catch (DocumentException e) {
        e.printStackTrace();
      } catch (IOException ex) {
        Logger.getLogger(Cuentaspagar.class.getName()).log(Level.SEVERE, null, ex);
      }

      Phrase headPhraseImg =
          new Phrase(cbhead + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL));

      Calendar c1 = Calendar.getInstance();
      Calendar c2 = new GregorianCalendar();
      String dia, mes, annio;
      dia = Integer.toString(c1.get(Calendar.DATE));
      mes = Integer.toString(c1.get(Calendar.MONTH));
      annio = Integer.toString(c1.get(Calendar.YEAR));
      java.util.Date fecha = new Date();
      String fechis = dia + "/" + mes + "/" + annio;
      Paragraph parrafo5 =
          new Paragraph(
              fechis,
              FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLACK));
      ColumnText.showTextAligned(
          writer.getDirectContent(),
          Element.ALIGN_CENTER,
          new Phrase(parrafo5),
          rect.getRight(450),
          rect.getTop(-80),
          0);

      Paragraph parrafo7 =
          new Paragraph(
              "Empresa Sapito S.A. de C.V.",
              FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD, BaseColor.BLACK));
      ColumnText.showTextAligned(
          writer.getDirectContent(),
          Element.ALIGN_CENTER,
          new Phrase(parrafo7),
          rect.getBottom(250),
          rect.getTop(-60),
          0);

      Paragraph parrafo8 =
          new Paragraph(
              "Cuentas por cobrar",
              FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD, BaseColor.BLACK));
      ColumnText.showTextAligned(
          writer.getDirectContent(),
          Element.ALIGN_CENTER,
          new Phrase(parrafo8),
          rect.getBottom(250),
          rect.getTop(-40),
          0);

      ColumnText.showTextAligned(
          writer.getDirectContent(),
          Element.ALIGN_BOTTOM,
          new Phrase(
              "      _________________________________________________________________________________    "),
          rect.getBorder(),
          rect.getTop(-24),
          0);

      ColumnText.showTextAligned(
          writer.getDirectContent(),
          Element.ALIGN_BOTTOM,
          new Phrase(
              "      _________________________________________________________________________________    "),
          rect.getBorder(),
          rect.getTop(-20),
          0);

      Paragraph parrafo6 =
          new Paragraph(
              String.format("Pág %d", writer.getPageNumber()),
              FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLACK));
      ColumnText.showTextAligned(
          writer.getDirectContent(),
          Element.ALIGN_CENTER,
          new Phrase(parrafo6),
          rect.getRight(-35),
          rect.getTop(-80),
          0);
    }
Пример #30
0
  public PdfContent(
      Document document,
      PdfWriter writer,
      Date update,
      List<Computer> computerList,
      LinkedList<MyObject> objList)
      throws DocumentException, IOException {
    PdfMethod pdfMethod = new PdfMethod(document);
    PdfContentByte pdfContent = writer.getDirectContent();
    PdfHeaderFooter event = new PdfHeaderFooter();
    Font font = new Font(FontFamily.HELVETICA, 12);
    BaseFont baseFont = font.getCalculatedBaseFont(false);
    writer.setPageEvent(event);
    tableContent(computerList);
    document.add(table);
    pdfMethod.addElementToDoc("W - Workstation", 0, 0);
    pdfMethod.addElementToDoc("P - Production", 0, 0);
    pdfMethod.addElementToDoc("SVR - Server", 0, 0);
    pdfMethod.addElementToDoc("STD - Standalone", 0, 0);
    document.newPage();

    for (MyObject object : objList) {
      Computer computer = (Computer) object.getObject();
      int id = computer.getId();
      String computerName = computer.getName().toUpperCase(),
          deptName = computer.getDept().getName(),
          gaNo = computer.getGaNo(),
          os = "N/A";
      OS_VER osVersion = computer.getOs();
      if (osVersion != null) os = osVersion.getAbbreviation();
      Iterator<?> folderNameIter = object.getObjList();
      // pdf layout
      new PdfLayout(document, writer, update);
      pdfContent.beginText();
      pdfContent.setFontAndSize(baseFont, 12);
      // pdf header
      pdfContent.showTextAligned(0, pdfMethod.setReportNo(id), 118, 733, 0);
      pdfContent.showTextAligned(0, deptName, 150, 679, 0);
      pdfContent.showTextAligned(0, computerName, 150, 661, 0);
      pdfContent.showTextAligned(0, gaNo, 150, 643, 0);
      pdfContent.showTextAligned(0, os, 150, 625, 0);
      pdfContent.endText();
      pdfMethod.addElementToDoc(" ", 0, 0);

      // pdf content
      while (folderNameIter.hasNext())
        pdfMethod.addElementToDoc((String) folderNameIter.next(), 0, 0);

      // pdf remark
      pdfContent.beginText();
      pdfContent.setFontAndSize(baseFont, 7);
      pdfContent.setColorFill(BaseColor.DARK_GRAY);
      pdfContent.showTextAligned(
          0,
          "The above program list are for those programs that "
              + "have to be installed additionally, i.e. Not belonging to default programs / drivers "
              + "of Windows system.",
          15,
          30,
          0);
      pdfContent.showTextAligned(
          0,
          "What belongs to default program / driver of Windows system ? "
              + "It can be searched from the following URL < http://bwhprdrpt:8080/CSCS >",
          15,
          22,
          0);
      pdfContent.endText();
      pdfContent.setColorFill(BaseColor.BLACK);
      document.newPage();
    }
  }