Java Code Examples for org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode#APPEND

The following examples show how to use org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode#APPEND . 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: 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 3
Source File: ExtractBoxedText.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/51380677/extracting-text-from-pdf-java-using-pdfbox-library-from-a-tables-rows-with-di">
 * Extracting text from pdf (java using pdfbox library) from a table's rows with different heights
 * </a>
 * <br/>
 * <a href="https://www.info.uvt.ro/wp-content/uploads/2018/07/Programare-licenta-5-Iulie-2018_1.pdf">
 * Programare-licenta-5-Iulie-2018_1.pdf
 * </a>
 * <p>
 * This test draws a grid on the test file representing the boxes found by the
 * {@link PdfBoxFinder}.
 * </p>
 */
@Test
public void testDrawBoxes() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("Programare-licenta-5-Iulie-2018_1.pdf");
            PDDocument document = Loader.loadPDF(resource) ) {
        for (PDPage page : document.getDocumentCatalog().getPages()) {
            PdfBoxFinder boxFinder = new PdfBoxFinder(page);
            boxFinder.processPage(page);

            try (PDPageContentStream canvas = new PDPageContentStream(document, page, AppendMode.APPEND, true, true)) {
                canvas.setStrokingColor(Color.RED);
                for (Rectangle2D rectangle : boxFinder.getBoxes().values()) {
                    canvas.addRect((float)rectangle.getX(), (float)rectangle.getY(), (float)rectangle.getWidth(), (float)rectangle.getHeight());
                }
                canvas.stroke();
            }
        }
        document.save(new File(RESULT_FOLDER, "Programare-licenta-5-Iulie-2018_1-rectangles.pdf"));
    }
}
 
Example 4
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
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 5
Source File: DashboardUtil.java    From Insights with 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 6
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 7
Source File: PlaceRotatedImage.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * @see #testPlaceByBoundingBox()
 */
void placeImage(PDDocument document, PDPage page, PDImageXObject image, float bbLowerLeftX, float bbLowerLeftY, float width, float height, float angle) throws IOException {
    try (   PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true)   ) {
        float bbWidth = (float)(Math.abs(Math.sin(angle))*height + Math.abs(Math.cos(angle))*width);
        float bbHeight = (float)(Math.abs(Math.sin(angle))*width + Math.abs(Math.cos(angle))*height);
        contentStream.transform(Matrix.getTranslateInstance((bbLowerLeftX + .5f*bbWidth), (bbLowerLeftY + .5f*bbHeight)));
        contentStream.transform(Matrix.getRotateInstance(angle, 0, 0));
        contentStream.drawImage(image, -.5f*width, -.5f*height, width, height);
    }
}
 
Example 8
Source File: DetermineBoundingBox.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
void drawBoundingBox(PDDocument pdDocument, PDPage pdPage) throws IOException {
    BoundingBoxFinder boxFinder = new BoundingBoxFinder(pdPage);
    boxFinder.processPage(pdPage);
    Rectangle2D box = boxFinder.getBoundingBox();
    if (box != null) {
        try (   PDPageContentStream canvas = new PDPageContentStream(pdDocument, pdPage, AppendMode.APPEND, true, true)) {
            canvas.setStrokingColor(Color.magenta);
            canvas.addRect((float)box.getMinX(), (float)box.getMinY(), (float)box.getWidth(), (float)box.getHeight());
            canvas.stroke();
        }
    }
}
 
Example 9
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));
}