Java Code Examples for org.apache.pdfbox.pdmodel.PDPageContentStream

The following examples show how to use org.apache.pdfbox.pdmodel.PDPageContentStream. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: testarea-pdfbox2   Source File: RotatePageContent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content and then move its crop box and
 * media box accordingly to make it appear as if the content was rotated around
 * the center of the crop box.
 * </p>
 */
@Test
public void testRotateMoveBox() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);
        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        cs.transform(matrix);
        cs.close();

        PDRectangle cropBox = page.getCropBox();
        float cx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float cy = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
        Point2D.Float newC = matrix.transformPoint(cx, cy);
        float tx = (float)newC.getX() - cx;
        float ty = (float)newC.getY() - cy;
        page.setCropBox(new PDRectangle(cropBox.getLowerLeftX() + tx, cropBox.getLowerLeftY() + ty, cropBox.getWidth(), cropBox.getHeight()));
        PDRectangle mediaBox = page.getMediaBox();
        page.setMediaBox(new PDRectangle(mediaBox.getLowerLeftX() + tx, mediaBox.getLowerLeftY() + ty, mediaBox.getWidth(), mediaBox.getHeight()));

        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-move-box.pdf"));
    }
}
 
Example 2
Source Project: attic-polygene-java   Source File: PDFWriter.java    License: Apache License 2.0 6 votes vote down vote up
private void writeGraphPage( GraphDisplay graphDisplay )
    throws IOException
{
    File tFile = File.createTempFile( "envisage", ".png" );
    graphDisplay.saveImage( new FileOutputStream( tFile ), "png", 1d );

    BufferedImage img = ImageIO.read( tFile );

    int w = img.getWidth();
    int h = img.getHeight();

    int inset = 40;
    PDRectangle pdRect = new PDRectangle( w + inset, h + inset );
    PDPage page = new PDPage();
    page.setMediaBox( pdRect );
    doc.addPage( page );

    PDImageXObject xImage = PDImageXObject.createFromFileByExtension( tFile, doc );

    PDPageContentStream contentStream = new PDPageContentStream( doc, page );
    contentStream.drawImage( xImage, ( pdRect.getWidth() - w ) / 2, ( pdRect.getHeight() - h ) / 2 );
    contentStream.close();
}
 
Example 3
Source Project: testarea-pdfbox2   Source File: ShowSpecialGlyph.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49426018/%e2%82%b9-indian-rupee-symbol-symbol-is-printing-as-question-mark-in-pdf-using-apa">
 * ₹ (Indian Rupee Symbol) symbol is printing as ? (question mark) in pdf using Apache PDFBOX
 * </a>
 * <p>
 * This test shows how to successfully show the Indian Rupee symbol
 * based on the OP's source frame and Tilman's proposed font.
 * </p>
 */
@Test
public void testIndianRupeeForVandanaSharma() throws IOException {
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    PDPageContentStream cos=  new PDPageContentStream(doc, page);
    cos.beginText();
    String text = "Deposited Cash of ₹10,00,000/- or more in a Saving Bank Account";
    cos.newLineAtOffset(25, 700);
    cos.setFont(PDType0Font.load(doc, new File("c:/windows/fonts/arial.ttf")), 12);
    cos.showText(text);
    cos.endText();
    cos.close();
    doc.save(new File(RESULT_FOLDER, "IndianRupee.pdf"));
    doc.close();
}
 
Example 4
Source Project: easytable   Source File: TableDrawer.java    License: MIT License 6 votes vote down vote up
public void draw(Supplier<PDDocument> documentSupplier, Supplier<PDPage> pageSupplier, float yOffset) throws IOException {
    final PDDocument document = documentSupplier.get();

    // We create one throwaway page to be able to calculate the page data upfront
    float startOnNewPage = pageSupplier.get().getMediaBox().getHeight() - yOffset;
    final Queue<PageData> pageDataQueue = computeRowsOnPagesWithNewPageStartOf(startOnNewPage);

    for (int i = 0; !pageDataQueue.isEmpty(); i++) {
        final PDPage pageToDrawOn;

        if (i > 0 || document.getNumberOfPages() == 0) {
            pageToDrawOn = pageSupplier.get();
            document.addPage(pageToDrawOn);
        } else {
            pageToDrawOn = document.getPage(document.getNumberOfPages() - 1);
        }

        try (final PDPageContentStream newPageContentStream = new PDPageContentStream(document, pageToDrawOn, APPEND, false)) {
            this.contentStream(newPageContentStream)
                    .page(pageToDrawOn)
                    .drawPage(pageDataQueue.poll());
        }

        startY(pageToDrawOn.getMediaBox().getHeight() - yOffset);
    }
}
 
Example 5
Source Project: easytable   Source File: AbstractCellDrawer.java    License: MIT License 6 votes vote down vote up
@Override
@SneakyThrows
public void drawBackground(DrawingContext drawingContext) {
    if (cell.hasBackgroundColor()) {
        final PDPageContentStream contentStream = drawingContext.getContentStream();
        final Point2D.Float start = drawingContext.getStartingPoint();

        final float rowHeight = cell.getRow().getHeight();
        final float height = Math.max(cell.getHeight(), rowHeight);
        final float y = rowHeight < cell.getHeight()
                ? start.y + rowHeight - cell.getHeight()
                : start.y;

        DrawingUtil.drawRectangle(contentStream,
                PositionedRectangle.builder()
                        .x(start.x)
                        .y(y)
                        .width(cell.getWidth())
                        .height(height)
                        .color(cell.getBackgroundColor()).build()
        );
    }
}
 
Example 6
Source Project: testarea-pdfbox2   Source File: JoinPages.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareBiggerPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A5);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.GREEN);
    contentStream.addRect(0, 0, PDRectangle.A5.getWidth(), PDRectangle.A5.getHeight());
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDType1Font.HELVETICA;
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, PDRectangle.A5.getHeight() - 24);
    contentStream.showText("This is the Bigger page");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("BIGGER!");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example 7
Source Project: easytable   Source File: ParagraphCellDrawer.java    License: MIT License 6 votes vote down vote up
private AnnotationDrawListener createAndGetAnnotationDrawListenerWith(DrawingContext drawingContext) {
    return new AnnotationDrawListener(new DrawContext() {
            @Override
            public PDDocument getPdDocument() {
                return null;
            }

            @Override
            public PDPage getCurrentPage() {
                return drawingContext.getPage();
            }

            @Override
            public PDPageContentStream getCurrentPageContentStream() {
                return drawingContext.getContentStream();
            }
        });
}
 
Example 8
@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 9
private static void createPDF(List<InputStream> inputImages, Path output) throws IOException {
	PDDocument document = new PDDocument();
	try {
		for (InputStream is : inputImages) {
			BufferedImage bimg = ImageIO.read(is);
			float width = bimg.getWidth();
			float height = bimg.getHeight();
			PDPage page = new PDPage(new PDRectangle(width, height));
			document.addPage(page);

			PDImageXObject img = LosslessFactory.createFromImage(document, bimg);
			try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
				contentStream.drawImage(img, 0, 0);
			}
		}
		document.save(output.toFile());
	} finally {
		document.close();
	}
}
 
Example 10
private static void writeText(PDPageContentStream contentStream, Color color, PDFont font, float fontSize, boolean rotate, float x, float y, String... text)
		throws IOException {
	contentStream.beginText();
	// set font and font size
	contentStream.setFont(font, fontSize);
	// set text color
	contentStream.setNonStrokingColor(color.getRed(), color.getGreen(), color.getBlue());
	if (rotate) {
		// rotate the text according to the page rotation
		contentStream.setTextMatrix(Matrix.getRotateInstance(Math.PI / 2, x, y));
	} else {
		contentStream.setTextMatrix(Matrix.getTranslateInstance(x, y));
	}
	if (text.length > 1) {
		contentStream.setLeading(25f);

	}
	for (String line : text) {
		contentStream.showText(line);
		contentStream.newLine();
	}
	contentStream.endText();
}
 
Example 11
private static void writeFrontpageDetails(PDDocument doc, PDFont font, float fontSize, FrontpageDetails details) throws IOException {
	String name = "Name: " + details.getName();
	String description = "Description: " + details.getDescription();
	String date = "Date: " + DEFAULT_DATE_FORMATTER.format(details.getDate());
	PDPage page = doc.getPage(0);
	PDRectangle pageSize = page.getMediaBox();
	float stringWidth = font.getStringWidth(StringUtilities.findLongest(name, description, date)) * fontSize / 1000f;
	float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

	int rotation = page.getRotation();
	boolean rotate = rotation == 90 || rotation == 270;
	float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
	float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
	float startX = rotate ? pageHeight / 3f : (pageWidth - stringWidth - stringHeight) / 3f;
	float startY = rotate ? (pageWidth - stringWidth) / 1f : pageWidth / 0.9f;

	// append the content to the existing stream
	try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {
		// draw rectangle
		writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, name, description, date);
	}
}
 
Example 12
Source Project: testarea-pdfbox2   Source File: RotatePageContent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/40611736/rotate-pdf-around-its-center-using-pdfbox-in-java">
 * Rotate PDF around its center using PDFBox in java
 * </a>
 * <p>
 * This test shows how to rotate the page content around the center of its crop box
 * and then crop it to make all previously visible content fit.
 * </p>
 */
@Test
public void testRotateCenterScale() throws IOException
{
    try (   InputStream resource = getClass().getResourceAsStream("IRJET_Copy_Right_form.pdf")  )
    {
        PDDocument document = Loader.loadPDF(resource);
        PDPage page = document.getDocumentCatalog().getPages().get(0);
        PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, false);

        Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45), 0, 0);
        PDRectangle cropBox = page.getCropBox();
        float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
        float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;

        Rectangle rectangle = cropBox.transform(matrix).getBounds();
        float scale = Math.min(cropBox.getWidth() / (float)rectangle.getWidth(), cropBox.getHeight() / (float)rectangle.getHeight());

        cs.transform(Matrix.getTranslateInstance(tx, ty));
        cs.transform(matrix);
        cs.transform(Matrix.getScaleInstance(scale, scale));
        cs.transform(Matrix.getTranslateInstance(-tx, -ty));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-center-scale.pdf"));
    }
}
 
Example 13
Source Project: cat-boot   Source File: ReportTableWithVerticalLines.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY,
                   float allowedWidth) throws IOException {
    if (title != null) {
        throw new IllegalStateException("title not implemented!");
    }
    float y = startY;
    int i = 0;

    float lineY = 0;
    for (ReportElement[] line : elements) {
        float lineHeight = getLineHeight(line, allowedWidth) + pdfStyleSheet.getLineDistance();
        y = printLine(document, stream, pageNumber, startX, y, allowedWidth, line, lineY);
        placeFirstBorder = i == 0;
        placeLastBorder = i == elements.length - 1;
        placeBorders(stream, startY, y, startX, allowedWidth);
        i++;
        lineY += lineHeight;
    }
    return y;
}
 
Example 14
Source Project: cat-boot   Source File: ReportTable.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException {
    if (title != null) {
        throw new IllegalStateException("title not implemented!");
    }
    float y = startY;
    float previousY = y;
    int lineIndex = 0;

    for (ReportElement[] line : elements) {
        float calculatedHeight = LAYOUTING_ASSERTIONS_ENABLED ? getLineHeight(line, allowedWidth) : -1;
        y = printLine(document, stream, pageNumber, startX, y, allowedWidth, line);
        float actualHeight = previousY - y;
        if (LAYOUTING_ASSERTIONS_ENABLED && calculatedHeight != actualHeight) {
            throw new RuntimeException(String.format("Layout algorithm bug: layouting height calculation reported "
                            + "different height (%s) than painting code (%s) in table with %s lines, current line index: %s",
                    calculatedHeight, actualHeight, elements.length, lineIndex));
        }
        boolean isFirstLine = lineIndex == 0;
        boolean isLastLine = lineIndex == elements.length - 1;
        placeBorders(stream, previousY, y, startX, allowedWidth, isFirstLine, isLastLine);
        previousY = y;
        lineIndex++;
    }
    return y;
}
 
Example 15
Source Project: estatio   Source File: PdfManipulator.java    License: Apache License 2.0 6 votes vote down vote up
private float addLines(
        final float x, final float y,
        final float height,
        final List<Line> lines,
        final PDPageContentStream cs) throws IOException {
    cs.setFont(TEXT_FONT, TEXT_FONT_SIZE);
    float yLine = y + height - TEXT_LINE_HEIGHT;
    for (Line line : lines) {

        cs.setNonStrokingColor(line.color);
        cs.beginText();
        cs.newLineAtOffset(x + TEXT_X_PADDING, yLine);
        cs.showText(line.text);
        cs.endText();

        yLine -= TEXT_LINE_HEIGHT;
    }

    return yLine;
}
 
Example 16
Source Project: testarea-pdfbox2   Source File: AddTextWithDynamicFonts.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #testAddLikeCccompany()
 */
private static ByteArrayOutputStream generatePdfFromString(String content) throws IOException {
    PDPage page = new PDPage();

    try (PDDocument doc = new PDDocument();
         PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
        doc.addPage(page);
        contentStream.setFont(PDType1Font.HELVETICA, 12);

        // Or load a specific font from a file
        // contentStream.setFont(PDType0Font.load(this.doc, new File("/fontPath.ttf")), 12);

        contentStream.beginText();
        contentStream.showText(content);
        contentStream.endText();
        contentStream.close();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        doc.save(os);
        return os;
    }
}
 
Example 17
Source Project: testarea-pdfbox2   Source File: AddTextWithDynamicFonts.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see #testAddLikeCccompanyImproved()
 */
private static ByteArrayOutputStream generatePdfFromStringImproved(String content) throws IOException {
    try (   PDDocument doc = new PDDocument();
            InputStream notoSansRegularResource = AddTextWithDynamicFonts.class.getResourceAsStream("NotoSans-Regular.ttf");
            InputStream notoSansCjkRegularResource = AddTextWithDynamicFonts.class.getResourceAsStream("NotoSansCJKtc-Regular.ttf")   ) {
        PDType0Font notoSansRegular = PDType0Font.load(doc, notoSansRegularResource);
        PDType0Font notoSansCjkRegular = PDType0Font.load(doc, notoSansCjkRegularResource);
        List<PDFont> fonts = Arrays.asList(notoSansRegular, notoSansCjkRegular);

        List<TextWithFont> fontifiedContent = fontify(fonts, content);

        PDPage page = new PDPage();
        doc.addPage(page);
        try (   PDPageContentStream contentStream = new PDPageContentStream(doc, page)) {
            contentStream.beginText();
            for (TextWithFont textWithFont : fontifiedContent) {
                textWithFont.show(contentStream, 12);
            }
            contentStream.endText();
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        doc.save(os);
        return os;
    }
}
 
Example 18
Source Project: testarea-pdfbox2   Source File: OverlayDocuments.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://issues.apache.org/jira/browse/PDFBOX-4797">
 * Overlayed PDF file do not shows the difference
 * </a>
 * <br/>
 * <a href="https://issues.apache.org/jira/secure/attachment/12996277/10.pdf">
 * 10.pdf
 * </a>
 * <br/>
 * <a href="https://issues.apache.org/jira/secure/attachment/12996276/114.pdf">
 * 114.pdf
 * </a>
 * <p>
 * This test demonstrates how to use the blend mode when overlaying documents
 * for comparison.
 * </p>
 */
@Test
public void testOverlayWithMultiply() throws IOException {
    try (   InputStream file1 = getClass().getResourceAsStream("10.pdf");
            InputStream file2 = getClass().getResourceAsStream("114.pdf");
            PDDocument document1 = Loader.loadPDF(file1);
            PDDocument document2 = Loader.loadPDF(file2);
            Overlay overlayer = new Overlay()) {
        overlayer.setInputPDF(document1);
        overlayer.setAllPagesOverlayPDF(document2);
        try (   PDDocument result = overlayer.overlay(Collections.emptyMap()) ) {
            result.save(new File(RESULT_FOLDER, "10and114.pdf"));

            try (   PDPageContentStream canvas = new PDPageContentStream(result, result.getPage(5), AppendMode.PREPEND, false, false)) {
                PDExtendedGraphicsState extGState = new PDExtendedGraphicsState();
                extGState.setBlendMode(BlendMode.MULTIPLY);
                canvas.setGraphicsStateParameters(extGState);
            }
            result.save(new File(RESULT_FOLDER, "10and114multiply.pdf"));
        }
    }
}
 
Example 19
Source Project: testarea-pdfbox2   Source File: RotatedTextOnLine.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/52054396/rotate-text-in-pdfbox-with-java">
 * Rotate text in pdfbox with java
 * </a>
 * <p>
 * This test shows how to show rotated text above a line.
 * </p>
 */
@Test
public void testRotatedTextOnLineForCedrickKapema() throws IOException {
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    PDPageContentStream cos = new PDPageContentStream(doc, page);
    cos.transform(Matrix.getRotateInstance(-Math.PI / 6, 100, 650));
    cos.moveTo(0, 0);
    cos.lineTo(125, 0);
    cos.stroke();
    cos.beginText();
    String text = "0.72";
    cos.newLineAtOffset(50, 5);
    cos.setFont(PDType1Font.HELVETICA_BOLD, 12);
    cos.showText(text);
    cos.endText();
    cos.close();
    doc.save(new File(RESULT_FOLDER, "TextOnLine.pdf"));
    doc.close();
}
 
Example 20
Source Project: Open-Lowcode   Source File: PDFPage.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param contentStream
 * @param text
 */
public static void securedShowText(PDPageContentStream contentStream, String text) {
	try {
		contentStream.showText(remove(text));
	} catch (Exception e) {
		throw new RuntimeException("Error in printing text " + text + ", original exception "
				+ e.getClass().toString() + " = " + e.getMessage());
	}
}
 
Example 21
Source Project: easytable   Source File: DrawingUtil.java    License: MIT License 5 votes vote down vote up
public static void drawText(PDPageContentStream contentStream, PositionedStyledText styledText) throws IOException {
    contentStream.beginText();
    contentStream.setNonStrokingColor(styledText.getColor());
    contentStream.setFont(styledText.getFont(), styledText.getFontSize());
    contentStream.newLineAtOffset(styledText.getX(), styledText.getY());
    contentStream.showText(styledText.getText());
    contentStream.endText();
    contentStream.setCharacterSpacing(0);
}
 
Example 22
Source Project: easytable   Source File: DrawingUtil.java    License: MIT License 5 votes vote down vote up
public static void drawRectangle(PDPageContentStream contentStream, PositionedRectangle rectangle)
        throws IOException {
    contentStream.setNonStrokingColor(rectangle.getColor());

    contentStream.addRect(rectangle.getX(), rectangle.getY(), rectangle.getWidth(), rectangle.getHeight());
    contentStream.fill();

    // Reset NonStrokingColor to default value
    contentStream.setNonStrokingColor(Color.BLACK);
}
 
Example 23
Source Project: easytable   Source File: MinimumWorkingExample.java    License: 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 24
Source Project: easytable   Source File: TestUtils.java    License: 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 25
Source Project: easytable   Source File: FinalYTest.java    License: 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 26
private static void drawRect(PDPageContentStream contentStream, Color color, Rectangle rect, boolean fill) throws IOException {
	contentStream.addRect(rect.x, rect.y, rect.width, rect.height);
	if (fill) {
		contentStream.setNonStrokingColor(color);
		contentStream.fill();
	} else {
		contentStream.setStrokingColor(color);
		contentStream.stroke();
	}
}
 
Example 27
private static void writePageNumbering(PDDocument doc, PDFont font, float fontSize, PageNumbering pageNumbering) throws IOException {
	int totalPages = doc.getNumberOfPages();
	int numberOfPages = pageNumbering.isLastIncluded() ? doc.getNumberOfPages() : doc.getNumberOfPages() - 1;
	for (int pageIndex = pageNumbering.isFirstIncluded() ? 0 : 1; pageIndex < numberOfPages; pageIndex++) {
		String footer = "Page " + (pageIndex + 1) + " of " + totalPages;
		PDPage page = doc.getPage(pageIndex);
		PDRectangle pageSize = page.getMediaBox();
		float stringWidth = font.getStringWidth(footer) * fontSize / 1000f;
		float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

		int rotation = page.getRotation();
		boolean rotate = rotation == 90 || rotation == 270;
		float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
		float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
		float startX = rotate ? pageHeight / 2f : (pageWidth - stringWidth - stringHeight) / 2f;
		float startY = rotate ? (pageWidth - stringWidth) : stringHeight;

		// append the content to the existing stream
		try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {

			// draw rectangle
			contentStream.setNonStrokingColor(255, 255, 255); // gray background
			// Draw a white filled rectangle
			drawRect(contentStream, Color.WHITE, new java.awt.Rectangle((int) startX, (int) startY - 3, (int) stringWidth + 2, (int) stringHeight), true);
			writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, footer);
		}
	}
}
 
Example 28
Source Project: Insights   Source File: DashboardUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate Static content based on the Title configured .
 * 
 * @param document
 * @param title
 * @throws IOException
 */
private void generateStaticContent(PDDocument document, String title) throws IOException {
	float margin = 10f;
	PDPage staticPage = new PDPage();
	document.addPage(staticPage); 
	PDPageContentStream cos = new PDPageContentStream(document, staticPage);
	PDStreamUtils.write(cos, "OneDevOps | Insights", PDType1Font.HELVETICA, 40, 120, staticPage.getMediaBox().getHeight() - (2 * margin)-250,
			Color.BLACK);
	PDStreamUtils.rect(cos, 100, staticPage.getMediaBox().getHeight() - (2 * margin)-300, staticPage.getMediaBox().getWidth()-190, 1, Color.blue);
	cos.close();
}
 
Example 29
Source Project: Insights   Source File: DashboardUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Footer is filled with varaibles selected in Grafana by user
 * 
 * @param doc
 * @param title
 * @param variables
 * @return doc
 * @throws IOException
 */
private PDDocument footer(PDDocument doc, String title, String variables) throws IOException {
	try{
		PDPageTree pages = doc.getPages();
		for(PDPage p : pages){
			PDPageContentStream contentStream = new PDPageContentStream(doc, p, AppendMode.APPEND, false);
			contentStream.beginText();
			contentStream.newLineAtOffset(220, 780);
			contentStream.setFont(PDType1Font.HELVETICA, 11);
			contentStream.showText("OneDevOps Insights – "+title);
			contentStream.endText();
			if(!variables.equals("") && variables != null){
				contentStream.beginText();
				contentStream.newLineAtOffset(2, 17);
				contentStream.setFont(PDType1Font.HELVETICA, 9);
				contentStream.showText("This Report is generated based on the user selected values as below.");
				contentStream.endText();
				contentStream.beginText();
				contentStream.newLineAtOffset(2, 5);
				contentStream.setFont(PDType1Font.HELVETICA, 7);
				contentStream.showText(variables);
				contentStream.endText();
			}
			contentStream.close();
		}
	}catch(Exception e){
		Log.error("Error, Failed in Footer.. ", e.getMessage());
	}
	return doc;
}
 
Example 30
Source Project: SwissQRBill   Source File: PDFCanvas.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a new instance using the specified page size.
 * @param width page width, in mm
 * @param height page height, in mm
 * @throws IOException thrown if the creation fails
 */
public PDFCanvas(double width, double height) throws IOException {
    setupFontMetrics("Helvetica");
    document = new PDDocument();
    document.getDocumentInformation().setTitle("Swiss QR Bill");
    PDPage page = new PDPage(new PDRectangle((float) (width * MM_TO_PT), (float) (height * MM_TO_PT)));
    document.addPage(page);
    contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.OVERWRITE, true);
}