Java Code Examples for org.apache.pdfbox.pdmodel.common.PDRectangle#A4

The following examples show how to use org.apache.pdfbox.pdmodel.common.PDRectangle#A4 . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NestedHtmlInCell.java    From testarea-pdfbox2 with Apache License 2.0 7 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/43447829/apache-pdfbox-boxable-html-ordered-unordered-list-is-incorrectly-displayed">
     * Apache PDFBox, Boxable - HTML ordered/unordered list is incorrectly displayed
     * </a>
     * <p>
     * Using the 1.5-RC artifact like the OP did, one can indeed observe the incorrect nesting.
     * </p>
     * <p>
     * Compiling and using the current (2017-04-25) master branch (which contains numerous changes
     * added since the RC has been released but is still versioned 1.4!), though, the nested list
     * is properly displayed.
     * </p>
     */
    @Test
    public void testNestedHtmlListsInCell() throws IOException
    {
        PDDocument document = new PDDocument();
        PDPage myPage  = new PDPage(PDRectangle.A4);
        document.addPage(myPage);
        float yPosition = 777;
        float margin = 40;
        float bottomMargin = 40;
        float yStartNewPage = myPage.getMediaBox().getHeight() - (margin);
        float tableWidth = myPage.getMediaBox().getWidth() - (2 * margin);
        BaseTable table = new BaseTable(yPosition, yStartNewPage, bottomMargin, tableWidth, margin, document, myPage, true, true);
        Row<PDPage> row = table.createRow(10f);
        /*Cell cell = */row.createCell((100 / 3f),"<ul><li>hello</li><li>hello 2</li><ol><li>nested</li><li>nested 2</li></ol></ul>", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
//        /*Cell cell = */row.createCell((100 / 3f),"<ul><li>hello</li><li>hello 2<ol><li>nested</li><li>nested 2</li></ol></li></ul>", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
//        /*Cell cell = */row.createCell((100 / 3f),"<ul><li>hello</li><li>hello 2<ul><li>nested</li><li>nested 2</li></ul></li></ul>", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
//        /*Cell cell = */row.createCell((100 / 3f),"not bold <i>italic</i> <b>once bold <b>twice bold</b> once bold again <i>italic</i> </b> not bold", be.quodlibet.boxable.HorizontalAlignment.get("left"), be.quodlibet.boxable.VerticalAlignment.get("top"));
        table.draw();
        document.save(new File(RESULT_FOLDER, "NestedHtmlListsInCell.pdf"));
        document.close();
    }
 
Example 2
Source File: PdfGenerator.java    From blog-tutorials with MIT License 6 votes vote down vote up
public byte[] createPdf() throws IOException {
  try (PDDocument document = new PDDocument()) {
    PDPage page = new PDPage(PDRectangle.A4);
    page.setRotation(90);

    float pageWidth = page.getMediaBox().getWidth();
    float pageHeight = page.getMediaBox().getHeight();

    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    PDImageXObject chartImage = JPEGFactory.createFromImage(document,
      createChart((int) pageHeight, (int) pageWidth));

    contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
    contentStream.drawImage(chartImage, 0, 0);
    contentStream.close();

    document.addPage(page);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.save(byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
  }

}
 
Example 3
Source File: CustomCellDrawerTest.java    From easytable with MIT License 6 votes vote down vote up
@Test
public void testCustomCellDrawer() throws IOException {

    try (final PDDocument document = new PDDocument()) {

        final PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        try (final PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

            TableDrawer.builder()
                    .contentStream(contentStream)
                    .table(createSimpleTable())
                    .startX(50)
                    .startY(page.getMediaBox().getHeight() - 50)
                    .build()
                    .draw();

        }

        document.save(TestUtils.TARGET_FOLDER + "/" + FILE_NAME);
    }

    CompareResult compareResult = new PdfComparator<>(getExpectedPdfFor(FILE_NAME), getActualPdfFor(FILE_NAME)).compare();
    assertTrue(compareResult.isEqual());
}
 
Example 4
Source File: CustomCellWithCustomDrawerUsingLombokTest.java    From easytable with MIT License 6 votes vote down vote up
@Test
public void testCustomCellDrawer() throws IOException {

    try (final PDDocument document = new PDDocument()) {

        final PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        try (final PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

            TableDrawer.builder()
                    .contentStream(contentStream)
                    .table(createSimpleTable())
                    .startX(50)
                    .startY(page.getMediaBox().getHeight() - 50)
                    .build()
                    .draw();

        }

        document.save(TestUtils.TARGET_FOLDER + "/" + FILE_NAME);
    }

    CompareResult compareResult = new PdfComparator<>(getExpectedPdfFor(FILE_NAME), getActualPdfFor(FILE_NAME)).compare();
    assertTrue(compareResult.isEqual());
}
 
Example 5
Source File: RingManagerTest.java    From easytable with MIT License 5 votes vote down vote up
@Test
public void testRingManagerDocument() throws Exception {
    try (final PDDocument document = new PDDocument()) {
        final PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        final float startY = page.getMediaBox().getHeight() - 150;
        final int startX = 56;

        try (final PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            final Table table = getRingManagerTable();

            TableDrawer.builder()
                    .contentStream(contentStream)
                    .table(table)
                    .startX(startX)
                    .startY(startY)
                    .build()
                    .draw();

            contentStream.setFont(HELVETICA, 8.0f);
            contentStream.beginText();

            contentStream.newLineAtOffset(startX, startY - (table.getHeight() + 22));
            contentStream.showText("Dieser Kampf muss der WB nicht entsprechen, da als Sparringskampf angesetzt.");
            contentStream.endText();
        }

        document.save(TestUtils.TARGET_FOLDER + "/" + FILE_NAME);

        CompareResult compareResult = new PdfComparator<>(getExpectedPdfFor(FILE_NAME), getActualPdfFor(FILE_NAME)).compare();
        assertTrue(compareResult.isEqual());
    }
}
 
Example 6
Source File: MinimumWorkingExample.java    From easytable with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        try (PDDocument document = new PDDocument()) {
            final PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

                // Build the table
                Table myTable = Table.builder()
                        .addColumnsOfWidth(100, 100)
                        .addRow(Row.builder()
                                .add(TextCell.builder().text("One One").borderWidth(1).backgroundColor(Color.GRAY).build())
                                .add(TextCell.builder().text("One Two").borderWidth(1).backgroundColor(Color.LIGHT_GRAY).build())
                                .build())
                        .addRow(Row.builder()
                                .add(TextCell.builder().text("Two One").borderWidth(1).textColor(Color.RED).build())
                                .add(TextCell.builder().text("Two Two").borderWidth(1).horizontalAlignment(HorizontalAlignment.RIGHT).build())
                                .build())
                        .build();

                // Set up the drawer
                TableDrawer tableDrawer = TableDrawer.builder()
                        .contentStream(contentStream)
                        .startX(20f)
                        .startY(page.getMediaBox().getUpperRightY() - 20f)
                        .table(myTable)
                        .build();

                // And go for it!
                tableDrawer.draw();
            }

            document.save("example.pdf");
        }
    }
 
Example 7
Source File: TestUtils.java    From easytable with MIT License 5 votes vote down vote up
private static void createAndSaveDocumentWithTables(PDDocument document, String outputFileName, Table... tables) throws IOException {

        final PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);

        float startY = page.getMediaBox().getHeight() - PADDING;

        try (final PDPageContentStream contentStream = new PDPageContentStream(document, page)) {

            for (final Table table : tables) {

                TableDrawer.builder()
                        .page(page)
                        .contentStream(contentStream)
                        .table(table)
                        .startX(PADDING)
                        .startY(startY)
                        .endY(PADDING)
                        .build()
                        .draw(() -> document, () -> new PDPage(PDRectangle.A4), PADDING);

                startY -= (table.getHeight() + PADDING);
            }

        }

        document.save(TARGET_FOLDER + "/" + outputFileName);
        document.close();

    }
 
Example 8
Source File: FinalYTest.java    From easytable with MIT License 5 votes vote down vote up
@Test
public void testFinalY() throws IOException {

    try (final PDDocument document = new PDDocument()) {
        for (int i = 0; i < 10; i++) {
            final PDPage page = new PDPage(PDRectangle.A4);
            try (final PDPageContentStream contentStream = new PDPageContentStream(document, page, APPEND, false)) {
                contentStream.beginText();
                contentStream.setFont(PDType1Font.HELVETICA, 12);
                contentStream.newLineAtOffset(100, 100);
                contentStream.showText("text number " + i);
                contentStream.endText();
            }
            document.addPage(page);
        }

        for (int i = 0; i < document.getNumberOfPages(); i++) {
            try (final PDPageContentStream contentStream = new PDPageContentStream(document, document.getPage(i), APPEND, false)) {
                TableDrawer tableDrawer = TableDrawer.builder()
                        .contentStream(contentStream)
                        .table(createHeaderTableForPage(i))
                        .startX(50)
                        .startY(document.getPage(i).getMediaBox().getHeight() - 50)
                        .build();
                tableDrawer.draw();

                contentStream.beginText();
                contentStream.setFont(PDType1Font.HELVETICA, 12);
                contentStream.newLineAtOffset(100, tableDrawer.getFinalY() - 12);
                contentStream.showText("text after final y " + tableDrawer.getFinalY());
                contentStream.endText();
            }
        }

        document.save(TestUtils.TARGET_FOLDER + "/" + FILE_NAME);
    }

    final CompareResult compareResult = new PdfComparator<>(getExpectedPdfFor(FILE_NAME), getActualPdfFor(FILE_NAME)).compare();
    assertTrue(compareResult.isEqual());
}
 
Example 9
Source File: DenseMerging.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/54283827/pdf-files-merge-remove-blank-at-end-of-page-i-am-using-pdfbox-v2-0-13-to-achi">
 * PDF files merge : remove blank at end of page. I am using PDFBox v2.0.13 to achieve that
 * </a>
 * <p>
 * This test checks the {@link PdfDenseMergeTool} which allows
 * a dense merging of multiple input PDFs.
 * </p>
 */
@Test
public void testWithText() throws IOException {
    PDDocument document1 = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(30, 300),
            "Doc 1 line 1", "Doc 1 line 2", "Doc 1 line 3");
    document1.save(new File(RESULT_FOLDER, "Test Text 1.pdf"));
    PDDocument document2 = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(40, 400),
            "Doc 2 line 1", "Doc 2 line 2", "Doc 2 line 3");
    document2.save(new File(RESULT_FOLDER, "Test Text 2.pdf"));
    PDDocument document3 = createTextDocument(new PDRectangle(0, -300, 400, 600), 
            Matrix.getTranslateInstance(50, -100),
            "Doc 3 line 1", "Doc 3 line 2", "Doc 3 line 3");
    document3.save(new File(RESULT_FOLDER, "Test Text 3.pdf"));
    PDDocument document4 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getTranslateInstance(-140, -100),
            "Doc 4 line 1", "Doc 4 line 2", "Doc 4 line 3");
    document4.save(new File(RESULT_FOLDER, "Test Text 4.pdf"));
    PDDocument document5 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getRotateInstance(Math.PI / 4, -120, 0),
            "Doc 5 line 1", "Doc 5 line 2", "Doc 5 line 3");
    document5.save(new File(RESULT_FOLDER, "Test Text 5.pdf"));

    PdfDenseMergeTool tool = new PdfDenseMergeTool(PDRectangle.A4, 30, 30, 10);
    tool.merge(new FileOutputStream(new File(RESULT_FOLDER, "Merge with Text.pdf")),
            Arrays.asList(document1, document2, document3, document4, document5,
                    document1, document2, document3, document4, document5,
                    document1, document2, document3, document4, document5));
}
 
Example 10
Source File: RepeatingTableHeaders.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/54233886/pdfbox-header-in-all-pages-using-easytable">
 * PDFBOX - header in all pages using easytable
 * </a>
 * <p>
 * This is the code from the test routine the OP referred to. Indeed,
 * it does not create the header rows on each page, there simply is no
 * explicit support for table headers in easytable. But it is possible
 * to add repeating headers nonetheless, cf. the test method
 * {@link #createTwoPageTableRepeatingHeader()}.
 * </p>
 */
@Test
public void createTwoPageTable() throws IOException {
    final Table.TableBuilder tableBuilder = Table.builder()
            .addColumnOfWidth(200)
            .addColumnOfWidth(200);

    CellText dummyHeaderCell = CellText.builder()
            .text("Header dummy")
            .backgroundColor(Color.BLUE)
            .textColor(Color.WHITE)
            .borderWidth(1F)
            .build();

    CellText dummyCell = CellText.builder()
            .text("dummy")
            .borderWidth(1F)
            .build();

    tableBuilder.addRow(
            Row.builder()
                    .add(dummyHeaderCell)
                    .add(dummyHeaderCell)
                    .build());

    for (int i = 0; i < 50; i++) {
        tableBuilder.addRow(
                Row.builder()
                        .add(dummyCell)
                        .add(dummyCell)
                        .build());
    }

    final PDDocument document = new PDDocument();

    TableDrawer drawer = TableDrawer.builder()
            .table(tableBuilder.build())
            .startX(50)
            .startY(100F)
            .endY(50F) // note: if not set, table is drawn over the end of the page
            .build();

    do {
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);
        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            drawer.contentStream(contentStream).draw();
        }

        drawer.startY(page.getMediaBox().getHeight() - 50);
    } while (!drawer.isFinished());

    document.save(new File(RESULT_FOLDER, "twoPageTable.pdf"));
    document.close();
}
 
Example 11
Source File: RepeatingTableHeaders.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/54233886/pdfbox-header-in-all-pages-using-easytable">
 * PDFBOX - header in all pages using easytable
 * </a>
 * <p>
 * This is derived from the code from the test routine the OP referred
 * to. It has been changed to put the table headers in a separate table
 * which is drawn again and again. Indeed, it does create the header
 * rows on each page, unlike the original code, cf. the test method
 * {@link #createTwoPageTable()}.
 * </p>
 */
@Test
public void createTwoPageTableRepeatingHeader() throws IOException {
    final Table.TableBuilder tableHeaderBuilder = Table.builder()
            .addColumnOfWidth(200)
            .addColumnOfWidth(200);

    CellText dummyHeaderCell = CellText.builder()
            .text("Header dummy")
            .backgroundColor(Color.BLUE)
            .textColor(Color.WHITE)
            .borderWidth(1F)
            .build();

    tableHeaderBuilder.addRow(
            Row.builder()
                    .add(dummyHeaderCell)
                    .add(dummyHeaderCell)
                    .build());

    final Table.TableBuilder tableBuilder = Table.builder()
            .addColumnOfWidth(200)
            .addColumnOfWidth(200);

    CellText dummyCell = CellText.builder()
            .text("dummy")
            .borderWidth(1F)
            .build();

    for (int i = 0; i < 50; i++) {
        tableBuilder.addRow(
                Row.builder()
                        .add(dummyCell)
                        .add(dummyCell)
                        .build());
    }

    Table tableHeader = tableHeaderBuilder.build();

    final PDDocument document = new PDDocument();

    float startY = 100F;

    TableDrawer drawer = TableDrawer.builder()
            .table(tableBuilder.build())
            .startX(50)
            .endY(50F) // note: if not set, table is drawn over the end of the page
            .build();

    do {
        TableDrawer headerDrawer = TableDrawer.builder()
                .table(tableHeader)
                .startX(50)
                .build();

        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);
        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
            headerDrawer.startY(startY);
            headerDrawer.contentStream(contentStream).draw();
            drawer.startY(startY - tableHeader.getHeight());
            drawer.contentStream(contentStream).draw();
        }

        startY = page.getMediaBox().getHeight() - 50;
    } while (!drawer.isFinished());

    document.save(new File(RESULT_FOLDER, "twoPageTable-repeatingHeader.pdf"));
    document.close();
}
 
Example 12
Source File: UseSoftMask.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/60198179/creating-a-transparency-group-or-setting-graphics-state-soft-mask-with-pdfbox">
 * Creating a transparency group or setting graphics state soft mask with PDFBox
 * </a>
 * <br/>
 * <a href="https://i.stack.imgur.com/rh9kL.png">
 * rh9kL.png
 * </a> as "Nicolas_image.png"
 * <br/>
 * <a href="https://i.stack.imgur.com/2UoKr.png">
 * 2UoKr.png
 * </a> as "Nicolas_mask.png"
 * <p>
 * This test demonstrates how one can apply transparency group
 * soft masks in extended graphics state parameters.
 * </p>
 */
@Test
public void testSoftMaskedImageAndRectangle() throws IOException {
    try (   PDDocument document = new PDDocument()  ) {
        final PDImageXObject image;
        try (   InputStream imageResource = getClass().getResourceAsStream("Nicolas_image.png")) {
            image = PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(imageResource), "image");
        }

        final PDImageXObject mask;
        try (   InputStream imageResource = getClass().getResourceAsStream("Nicolas_mask.png")) {
            mask = PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(imageResource), "mask");
        }

        PDTransparencyGroupAttributes transparencyGroupAttributes = new PDTransparencyGroupAttributes();
        transparencyGroupAttributes.getCOSObject().setItem(COSName.CS, COSName.DEVICEGRAY);

        PDTransparencyGroup transparencyGroup = new PDTransparencyGroup(document);
        transparencyGroup.setBBox(PDRectangle.A4);
        transparencyGroup.setResources(new PDResources());
        transparencyGroup.getCOSObject().setItem(COSName.GROUP, transparencyGroupAttributes);
        try (   PDFormContentStream canvas = new PDFormContentStream(transparencyGroup)   ) {
            canvas.drawImage(mask, new Matrix(400, 0, 0, 400, 100, 100));
        }

        COSDictionary softMaskDictionary = new COSDictionary();
        softMaskDictionary.setItem(COSName.S, COSName.LUMINOSITY);
        softMaskDictionary.setItem(COSName.G, transparencyGroup);

        PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
        extendedGraphicsState.getCOSObject().setItem(COSName.SMASK, softMaskDictionary);

        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);
        try (   PDPageContentStream canvas = new PDPageContentStream(document, page)   ) {
            canvas.saveGraphicsState();
            canvas.setGraphicsStateParameters(extendedGraphicsState);
            canvas.setNonStrokingColor(Color.BLACK);
            canvas.addRect(100, 100, 400, 400);
            canvas.fill();
            canvas.drawImage(image, new Matrix(400, 0, 0, 300, 100, 150));
            canvas.restoreGraphicsState();
        }

        document.save(new File(RESULT_FOLDER, "SoftMaskedImageAndRectangle.pdf"));
    }
}
 
Example 13
Source File: DenseMerging.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/60052967/how-to-dense-merge-pdf-files-using-pdfbox-2-without-whitespace-near-page-breaks">
 * How to dense merge PDF files using PDFBox 2 without whitespace near page breaks?
 * </a>
 * <p>
 * This test checks the {@link PdfVeryDenseMergeTool} which allows
 * a very dense merging of multiple input PDFs.
 * </p>
 * <p>
 * Beware, as mentioned in the {@link PageVerticalAnalyzer} comments,
 * the processing in particular of curves is incorrect. The curve
 * used in this test is chosen not to create wrong results due to
 * this known issue.
 * </p>
 */
@Test
public void testVeryDenseMerging() throws IOException {
    PDDocument document1 = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(30, 300),
            "Doc 1 line 1", "Doc 1 line 2", "Doc 1 line 3");
    PDDocument document2 = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(40, 400),
            "Doc 2 line 1", "Doc 2 line 2", "Doc 2 line 3");
    PDDocument document3 = createTextDocument(new PDRectangle(0, -300, 400, 600), 
            Matrix.getTranslateInstance(50, -100),
            "Doc 3 line 1", "Doc 3 line 2", "Doc 3 line 3");
    PDDocument document4 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getTranslateInstance(-140, -100),
            "Doc 4 line 1", "Doc 4 line 2", "Doc 4 line 3");
    PDDocument document5 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getTranslateInstance(-140, -100),
            "Doc 5 line 1", "Doc 5 line 2", "Doc 5 line 3");
    PDDocument document6 = createTextDocument(new PDRectangle(-200, -300, 400, 600), 
            Matrix.getRotateInstance(Math.PI / 4, -120, 0),
            "Doc 6 line 1", "Doc 6 line 2", "Doc 6 line 3");
    try (   PDPageContentStream content = new PDPageContentStream(document6, document6.getPage(0), AppendMode.APPEND, false, true)) {
        content.setStrokingColor(Color.BLACK);
        content.moveTo(40, 40);
        content.lineTo(80, 80);
        content.lineTo(120, 100);
        content.stroke();

        content.moveTo(40, 140);
        content.curveTo(80, 140, 160, 140, 80, 180);
        content.closeAndFillAndStroke();
    }
    document6.save(new File(RESULT_FOLDER, "Test Text and Graphics.pdf"));

    PdfVeryDenseMergeTool tool = new PdfVeryDenseMergeTool(PDRectangle.A4, 30, 30, 10);
    tool.merge(new FileOutputStream(new File(RESULT_FOLDER, "Merge with Text and Graphics, very dense.pdf")),
            Arrays.asList(document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6,
                    document1, document2, document3, document4, document5, document6));
}