org.apache.pdfbox.pdmodel.PDPageContentStream Java Examples

The following examples show how to use org.apache.pdfbox.pdmodel.PDPageContentStream. 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: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 7 votes vote down vote up
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 #2
Source File: ReportTableWithVerticalLines.java    From cat-boot with Apache License 2.0 7 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 #3
Source File: DenseMerging.java    From testarea-pdfbox2 with Apache License 2.0 7 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 PageVerticalAnalyzer} functionality.
 * </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 testVerticalAnalyzer() throws IOException {
    PDDocument document = createTextDocument(new PDRectangle(0, 0, 400, 600), 
            Matrix.getTranslateInstance(30, 300),
            "Document line 1", "Document line 2", "Document line 3");

    PDPage page = document.getPage(0);

    try (   PDPageContentStream content = new PDPageContentStream(document, page, 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();
    }

    PageVerticalAnalyzer analyzer = new PageVerticalAnalyzer(page);
    analyzer.processPage(page);
    System.out.println(analyzer.getVerticalFlips());
    
    try (   PDPageContentStream content = new PDPageContentStream(document, page, AppendMode.APPEND, false, true)) {
        content.setStrokingColor(Color.RED);
        content.setLineWidth(3);
        List<Float> flips = analyzer.getVerticalFlips();
        float x = page.getCropBox().getLowerLeftX() + 20;
        for (int i = 0; i < flips.size() - 1; i+=2) {
            content.moveTo(x, flips.get(i));
            content.lineTo(x, flips.get(i+1));
        }
        content.stroke();
    }

    document.save(new File(RESULT_FOLDER, "Test Document Vertically Marked.pdf"));
}
 
Example #4
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #5
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 #6
Source File: PdfManipulator.java    From estatio with 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 #7
Source File: RotatePageContent.java    From testarea-pdfbox2 with 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 #8
Source File: ReportTable.java    From cat-boot with 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 #9
Source File: AddTextWithDynamicFonts.java    From testarea-pdfbox2 with 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 #10
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
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
Source File: ParagraphCellDrawer.java    From easytable with 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 #12
Source File: AddTextWithDynamicFonts.java    From testarea-pdfbox2 with 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 #13
Source File: JoinPages.java    From testarea-pdfbox2 with 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 #14
Source File: OverlayDocuments.java    From testarea-pdfbox2 with 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 #15
Source File: AbstractCellDrawer.java    From easytable with 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 #16
Source File: TableDrawer.java    From easytable with 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 #17
Source File: RotatedTextOnLine.java    From testarea-pdfbox2 with 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 #18
Source File: RotatePageContent.java    From testarea-pdfbox2 with 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 #19
Source File: ShowSpecialGlyph.java    From testarea-pdfbox2 with 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 #20
Source File: PDFWriter.java    From attic-polygene-java with 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 #21
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49958604/draw-image-at-mid-position-using-pdfbox-java">
 * Draw image at mid position using pdfbox Java
 * </a>
 * <p>
 * This is the OP's original code. It mirrors the image.
 * This can be fixed as shown in {@link #testImageAppendNoMirror()}.
 * </p>
 */
@Test
public void testImageAppendLikeShanky() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf");
            InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = Loader.loadPDF(resource);
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

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

        PDPage page = doc.getPage(0);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);

        float x_pos = page.getCropBox().getWidth();
        float y_pos = page.getCropBox().getHeight();

        float x_adjusted = ( x_pos - w ) / 2;
        float y_adjusted = ( y_pos - h ) / 2;

        Matrix mt = new Matrix(1f, 0f, 0f, -1f, page.getCropBox().getLowerLeftX(), page.getCropBox().getUpperRightY());
        contentStream.transform(mt);
        contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);
        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "test-with-image-shanky.pdf"));
        doc.close();

    }
}
 
Example #22
Source File: PDFCanvas.java    From SwissQRBill with 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);
}
 
Example #23
Source File: ReportCompositeElement.java    From cat-boot with Apache License 2.0 5 votes vote down vote up
@Override
public float print(PDDocument document, PDPageContentStream stream, int pageNumber, float startX, float startY, float allowedWidth) throws IOException {
    float lastY = startY;
    for (ReportElement element : elements) {
        lastY = element.print(document, stream, pageNumber, startX, lastY, allowedWidth);
        intents.addAll(element.getImageIntents());
    }
    return lastY;
}
 
Example #24
Source File: RotatePageContent.java    From testarea-pdfbox2 with Apache License 2.0 5 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>
 * Indeed, using the code of the OP the image mostly is rotated out of the page area.
 * </p>
 */
@Test
public void testRotateLikeSagar() 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); 
        cs.transform(Matrix.getRotateInstance(Math.toRadians(45), 0, 0));
        cs.close();
        document.save(new File(RESULT_FOLDER, "IRJET_Copy_Right_form-rotated-like-sagar.pdf"));
    }
}
 
Example #25
Source File: NativePdfBoxVisibleSignatureDrawer.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void setBackground(PDPageContentStream cs, Color color, PDRectangle rect) throws IOException {
	if (color != null) {
           setAlphaChannel(cs, color);
           cs.setNonStrokingColor(color);
           // fill a whole box with the background color
           cs.addRect(rect.getLowerLeftX(), rect.getLowerLeftY(), rect.getWidth(), rect.getHeight());
           cs.fill();
           cleanTransparency(cs);
   	}
}
 
Example #26
Source File: AddImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/49958604/draw-image-at-mid-position-using-pdfbox-java">
 * Draw image at mid position using pdfbox Java
 * </a>
 * <p>
 * This is a fixed version of the the OP's original code, cf.
 * {@link #testImageAppendLikeShanky()}. It does not mirrors the image.
 * </p>
 */
@Test
public void testImageAppendNoMirror() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf");
            InputStream imageResource = getClass().getResourceAsStream("Willi-1.jpg")   )
    {
        PDDocument doc = Loader.loadPDF(resource);
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, ByteStreams.toByteArray(imageResource), "Willi");

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

        PDPage page = doc.getPage(0);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);

        float x_pos = page.getCropBox().getWidth();
        float y_pos = page.getCropBox().getHeight();

        float x_adjusted = ( x_pos - w ) / 2 + page.getCropBox().getLowerLeftX();
        float y_adjusted = ( y_pos - h ) / 2 + page.getCropBox().getLowerLeftY();

        contentStream.drawImage(pdImage, x_adjusted, y_adjusted, w, h);
        contentStream.close();

        doc.save(new File(RESULT_FOLDER, "test-with-image-no-mirror.pdf"));
        doc.close();

    }
}
 
Example #27
Source File: PdfBoxHelper.java    From cat-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Adds text of any length, will parse it if necessary.
 *
 * @param stream       stream
 * @param textConfig   text config
 * @param textX        starting X position of text
 * @param textY        starting Y position of text
 * @param allowedWidth max width of text (where to wrap)
 * @param lineHeightD  line height delta of text (line height will be: fontSize + this)
 * @param text         text
 * @param underline    true to underline the text
 * @return ending Y position of this line
 */
public static float addText(PDPageContentStream stream, PdfTextStyle textConfig, float textX, float textY, float allowedWidth, float lineHeightD, ReportAlignType align, String text, boolean underline) {

    float nextLineY = nextLineY(textY, textConfig.getFontSize(), lineHeightD);

    if (text.equals("")) {
        addTextSimple(stream, textConfig, textX, nextLineY, "");
        return nextLineY;
    }

    try {
        String[] split = splitText(textConfig.getCurrentFontStyle(), textConfig.getFontSize(), allowedWidth, Utf8Utils.removeCharactersWithZeroLength(text));
        float x = calculateAlignPosition(textX, align, textConfig, allowedWidth, split[0]);

        if (!underline) {
            addTextSimple(stream, textConfig, x, nextLineY, split[0]);
        } else {
            addTextSimpleUnderlined(stream, textConfig, x, nextLineY, split[0]);
        }

        if (!StringUtils.isEmpty(split[1])) {
            return addText(stream, textConfig, textX, nextLineY, allowedWidth, lineHeightD, align, split[1], underline);
        } else {
            return nextLineY;
        }

    } catch (Exception e) {
        LOG.warn("Could not add text: " + e.getClass() + " - " + e.getMessage());
        return textY;
    }
}
 
Example #28
Source File: PdfUtilExport.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
private void addCoverpage() throws IOException {
    float leading = 1.5f * FONT_SIZE_TITLE;
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    FONT_STYLE_COVER = PDTrueTypeFont.loadTTF(document, MainApp.class.getResourceAsStream(FONT_MERRIWEATHER_BOLD));
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(25, 81, 107);
    contentStream.fillRect(0, 0, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) + 10, page.getMediaBox().getWidth(), (page.getMediaBox().getHeight() / 2) - 10);
    contentStream.setNonStrokingColor(248, 173, 50);
    contentStream.fillRect(0, (page.getMediaBox().getHeight() / 2) - 10, page.getMediaBox().getWidth(), 20);

    contentStream.beginText();
    contentStream.setNonStrokingColor(Color.WHITE);
    contentStream.setFont(FONT_STYLE_COVER, FONT_SIZE_AUTHOR);
    contentStream.newLineAtOffset(20, 20);
    contentStream.showText(authorContent);
    contentStream.setFont(FONT_STYLE_COVER, FONT_SIZE_TITLE);
    contentStream.newLineAtOffset((page.getMediaBox().getWidth() / 2) - 20, 600);
    List<String> lines = wrapText((page.getMediaBox().getWidth() / 2) - 20);
    for (String line : lines) {
        contentStream.showText(line);
        contentStream.newLineAtOffset(0, -leading);
    }
    contentStream.endText();

    contentStream.close();
    File temp = File.createTempFile("coverpage-zds", ".pdf");
    document.save(temp);
    document.close();

    PDFMergerUtility mergerUtility = new PDFMergerUtility();
    mergerUtility.addSource(temp);
    mergerUtility.addSource(destPdfPath);
    mergerUtility.setDestinationFileName(destPdfPath);
    mergerUtility.mergeDocuments();
}
 
Example #29
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Places the given form over the existing content of the indicated page (like an overlay).
 * The form is enveloped in a marked content section to indicate that it's part of an
 * optional content group (OCG), here used as a layer. This optional group is returned and
 * can be enabled and disabled through methods on {@link PDOptionalContentProperties}.
 * <p>
 * You may want to call {@link #wrapInSaveRestore(PDPage) wrapInSaveRestore(PDPage)} before calling this method to make
 * sure that the graphics state is reset.
 *
 * @param targetPage the target page
 * @param form the form to place
 * @param transform the transformation matrix that controls the placement of your form. You'll
 * need this if your page has a crop box different than the media box, or if these have negative
 * coordinates, or if you want to scale or adjust your form.
 * @param layerName the name for the layer/OCG to produce
 * @return the optional content group that was generated for the form usage
 * @throws IOException if an I/O error occurs
 */
public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage,
        PDFormXObject form, AffineTransform transform,
        String layerName) throws IOException
{
    PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
    PDOptionalContentProperties ocprops = catalog.getOCProperties();
    if (ocprops == null)
    {
        ocprops = new PDOptionalContentProperties();
        catalog.setOCProperties(ocprops);
    }
    if (ocprops.hasGroup(layerName))
    {
        throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName);
    }

    PDRectangle cropBox = targetPage.getCropBox();
    if ((cropBox.getLowerLeftX() < 0 || cropBox.getLowerLeftY() < 0) && transform.isIdentity())
    {
        // PDFBOX-4044 
        LOG.warn("Negative cropBox " + cropBox + 
                 " and identity transform may make your form invisible");
    }

    PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName);
    ocprops.addGroup(layer);

    PDPageContentStream contentStream = new PDPageContentStream(
            targetDoc, targetPage, AppendMode.APPEND, !DEBUG);
    contentStream.beginMarkedContent(COSName.OC, layer);
    contentStream.saveGraphicsState();
    contentStream.transform(new Matrix(transform));
    contentStream.drawForm(form);
    contentStream.restoreGraphicsState();
    contentStream.endMarkedContent();
    contentStream.close();

    return layer;
}
 
Example #30
Source File: PDDefaultAppearanceString.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Writes the DA string to the given content stream.
 */
void writeTo(PDPageContentStream contents, float zeroFontSize) throws IOException
{
    float fontSize = getFontSize();
    if (fontSize == 0)
    {
        fontSize = zeroFontSize;
    }
    contents.setFont(getFont(), fontSize);
    
    if (getFontColor() != null)
    {
        contents.setNonStrokingColor(getFontColor());
    }
}