Java Code Examples for org.apache.pdfbox.pdmodel.PDDocument#addPage()

The following examples show how to use org.apache.pdfbox.pdmodel.PDDocument#addPage() . 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: JoinPages.java    From testarea-pdfbox2 with Apache License 2.0 7 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
PDDocument prepareSmallPdf() throws IOException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(new PDRectangle(72, 72));
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setNonStrokingColor(Color.YELLOW);
    contentStream.addRect(0, 0, 72, 72);
    contentStream.fill();
    contentStream.setNonStrokingColor(Color.BLACK);
    PDFont font = PDType1Font.HELVETICA;
    contentStream.beginText();
    contentStream.setFont(font, 18);
    contentStream.newLineAtOffset(2, 54);
    contentStream.showText("small");
    contentStream.newLineAtOffset(0, -48);
    contentStream.showText("page");
    contentStream.endText();
    contentStream.close();
    return document;
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
Source File: PreviewCreatorPdfImpl.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void internalCreatePreview() throws Exception {
	PDDocument sourceDocument = PDDocument.load(getSource());
	String tempFilename = DateTime.now().getMillis() + ".pdf";
	try {
		List<?> allPages = sourceDocument.getDocumentCatalog().getAllPages();
		PDDocument targetDocument = new PDDocument();
		try {
			if (isPageRangePercent()) {
				extractPageRangePercent(allPages);
			}
			for (int i = 0; i < allPages.size(); i++) {
				if (getPagesList().contains(i + 1)) {
					PDPage page = (PDPage) allPages.get(i);
					targetDocument.addPage(page);						
				}
				
			}
			targetDocument.save(tempFilename);
		} finally {
			targetDocument.close();
		}
	} finally {
		sourceDocument.close();
	}
	try {
		WatermarkWriter watermarkWriter = WatermarkWriterFactory.create(FilenameUtils.getExtension(tempFilename));
		try {
			watermarkWriter.writeWatermark(tempFilename, getTarget(), WatermarkFactory.create(getUser(), getProduct()), getLayout());
		} catch (IOException e) {
			throw new Exception("Unable to generate PDF", e);
		}
	} finally {
		File file = FileUtils.getFile(tempFilename);
		if (file.exists()) {
			file.delete();
		}					
	}
}
 
Example 9
Source File: CompareResultImpl.java    From pdfcompare with Apache License 2.0 5 votes vote down vote up
protected void addPageToDocument(final PDDocument document, final ImageWithDimension image) throws IOException {
    PDPage page = new PDPage(new PDRectangle(image.width, image.height));
    document.addPage(page);
    final PDImageXObject imageXObject = LosslessFactory.createFromImage(document, image.bufferedImage);
    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        contentStream.drawImage(imageXObject, 0, 0, image.width, image.height);
    }
}
 
Example 10
Source File: PDVisibleSigBuilder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a PDDocument and adds the page parameter to it and keeps this as a template in the
 * PDF template Structure.
 *
 * @param page
 * @throws IOException
 */
@Override
public void createTemplate(PDPage page) throws IOException
{
    PDDocument template = new PDDocument();
    template.addPage(page);
    pdfStructure.setTemplate(template);
}
 
Example 11
Source File: JoinPages.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * @see #testJoinSmallAndBig()
 */
void join(PDDocument target, PDDocument topSource, PDDocument bottomSource) throws IOException {
    LayerUtility layerUtility = new LayerUtility(target);
    PDFormXObject topForm = layerUtility.importPageAsForm(topSource, 0);
    PDFormXObject bottomForm = layerUtility.importPageAsForm(bottomSource, 0);

    float height = topForm.getBBox().getHeight() + bottomForm.getBBox().getHeight();
    float width, topMargin, bottomMargin;
    if (topForm.getBBox().getWidth() > bottomForm.getBBox().getWidth()) {
        width = topForm.getBBox().getWidth();
        topMargin = 0;
        bottomMargin = (topForm.getBBox().getWidth() - bottomForm.getBBox().getWidth()) / 2;
    } else {
        width = bottomForm.getBBox().getWidth();
        topMargin = (bottomForm.getBBox().getWidth() - topForm.getBBox().getWidth()) / 2;
        bottomMargin = 0;
    }

    PDPage targetPage = new PDPage(new PDRectangle(width, height));
    target.addPage(targetPage);


    PDPageContentStream contentStream = new PDPageContentStream(target, targetPage);
    if (bottomMargin != 0)
        contentStream.transform(Matrix.getTranslateInstance(bottomMargin, 0));
    contentStream.drawForm(bottomForm);
    contentStream.transform(Matrix.getTranslateInstance(topMargin - bottomMargin, bottomForm.getBBox().getHeight()));
    contentStream.drawForm(topForm);
    contentStream.close();
}
 
Example 12
Source File: DashboardUtil.java    From Insights with 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 13
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 14
Source File: LowLevelText.java    From pdfbox-layout with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

	final PDDocument test = new PDDocument();
	final PDPage page = new PDPage(Constants.A4);
	float pageWidth = page.getMediaBox().getWidth();
	float pageHeight = page.getMediaBox().getHeight();
	
	test.addPage(page);
	final PDPageContentStream contentStream = new PDPageContentStream(test, page,
		true, true);

	// AnnotationDrawListener is only needed if you use annoation based stuff, e.g. hyperlinks
	AnnotationDrawListener annotationDrawListener = new AnnotationDrawListener(new DrawContext() {

	    @Override
	    public PDDocument getPdDocument() {
		return test;
	    }

	    @Override
	    public PDPage getCurrentPage() {
		return page;
	    }

	    @Override
	    public PDPageContentStream getCurrentPageContentStream() {
		return contentStream;
	    }
	    
	});
	annotationDrawListener.beforePage(null);

	TextFlow text = TextFlowUtil
		.createTextFlowFromMarkup(
			"Hello *bold _italic bold-end* italic-end_. Eirmod\ntempor invidunt ut \\*labore",
			11, BaseFont.Times);

	text.addText("Spongebob", 11, PDType1Font.COURIER);
	text.addText(" is ", 20, PDType1Font.HELVETICA_BOLD_OBLIQUE);
	text.addText("cool", 7, PDType1Font.HELVETICA);

	text.setMaxWidth(100);
	float xOffset = TextSequenceUtil.getOffset(text, pageWidth,
		Alignment.Right);
	text.drawText(contentStream, new Position(xOffset, pageHeight - 50),
		Alignment.Right, annotationDrawListener);

	String textBlock = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, "
		+ "{link[https://github.com/ralfstuckert/pdfbox-layout/]}pdfbox layout{link} "
		+ "sed diam nonumy eirmod invidunt ut labore et dolore magna "
		+ "aliquyam erat, _sed diam_ voluptua. At vero eos et *accusam et justo* "
		+ "duo dolores et ea rebum.\n\nStet clita kasd gubergren, no sea takimata "
		+ "sanctus est *Lorem ipsum _dolor* sit_ amet. Lorem ipsum dolor sit amet, "
		+ "consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt "
		+ "ut labore et dolore magna aliquyam erat, *sed diam voluptua.\n\n"
		+ "At vero eos et accusam* et justo duo dolores et ea rebum. Stet clita kasd "
		+ "gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\n";

	text = new TextFlow();
	text.addMarkup(textBlock, 8, BaseFont.Courier);
	text.setMaxWidth(200);
	xOffset = TextSequenceUtil.getOffset(text, pageWidth, Alignment.Center);
	text.drawText(contentStream, new Position(xOffset, pageHeight - 100),
		Alignment.Justify, annotationDrawListener);

	// draw a round rect box with text
	text.setMaxWidth(350);
	float x = 50;
	float y = pageHeight - 300;
	float paddingX = 20;
	float paddingY = 15;
	float boxWidth = text.getWidth() + 2 * paddingX;
	float boxHeight = text.getHeight() + 2 * paddingY;

	Shape shape = new RoundRect(20);
	shape.fill(test, contentStream, new Position(x, y), boxWidth,
		boxHeight, Color.pink, null);
	shape.draw(test, contentStream, new Position(x, y), boxWidth,
		boxHeight, Color.blue, new Stroke(3), null);
	// now the text
	text.drawText(contentStream, new Position(x + paddingX, y - paddingY),
		Alignment.Center, annotationDrawListener);

	annotationDrawListener.afterPage(null);
	contentStream.close();
	
	annotationDrawListener.afterRender();

	final OutputStream outputStream = new FileOutputStream(
		"lowleveltext.pdf");
	test.save(outputStream);
	test.close();

    }
 
Example 15
Source File: ReportConvertPdf.java    From yuzhouwan with Apache License 2.0 4 votes vote down vote up
private static PDPageContentStream createContent(PDDocument doc, PDPage page) throws IOException {
    doc.addPage(page);
    return new PDPageContentStream(doc, page, true, true, true);
}
 
Example 16
Source File: ReportGenerator.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Generate PDF file for API microgateway request summary
 *
 * @param table object containing table headers and row data
 * @return InputStream pdf as a stream
 * @throws IOException
 * @throws COSVisitorException
 */
public InputStream generateMGRequestSummeryPDF(TableData table) throws IOException, COSVisitorException {

    String[] columnHeaders = table.getColumnHeaders();

    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    page.setRotation(0);
    document.addPage(page);

    PDPageContentStream contentStream = new PDPageContentStream(document, page, false, false);

    // add logo
    InputStream in = APIManagerComponent.class.getResourceAsStream("/report/wso2-logo.jpg");
    PDJpeg img = new PDJpeg(document, in);
    contentStream.drawImage(img, 375, 755);

    // Add topic
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 16);
    writeContent(contentStream, CELL_MARGIN, 770, "API Microgateway request summary");

    // Add generated time
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE);
    writeContent(contentStream, CELL_MARGIN, 730, "Report generated on: " + new Date().toString());

    contentStream.setFont(TEXT_FONT, FONT_SIZE);

    // add table with data
    drowTableGrid(contentStream, table.getRows().size());
    writeRowsContent(contentStream, columnHeaders, table.getRows());

    // Add meta data
    // Whenever the summary report structure is updated this should be changed
    String requestCount = table.getRows().get(0).getEntries().get(2);
    document.getDocumentInformation().setCustomMetadataValue(MGW_META, getMetaCount(requestCount));

    contentStream.close();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    document.save(out);
    document.close();

    return new ByteArrayInputStream(out.toByteArray());

}
 
Example 17
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 18
Source File: RenderType3Character.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
     * Render Type3 font character as image using PDFBox
     * </a>
     * <br/>
     * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
     * 4700198773.pdf
     * </a>
     * from
     * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
     * extract text with custom font result non readble
     * </a>
     * <p>
     * This test shows how one can render individual Type 3 font glyphs as bitmaps.
     * Unfortunately PDFBox out-of-the-box does not provide a class to render contents
     * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
     * with the glyph in question and render that page.   
     * </p>
     * <p>
     * As the OP did not provide a sample PDF, we simply use one from another
     * stackoverflow question. There obviously might remain issues with the
     * OP's files.
     * </p>
     */
    @Test
    public void testRender4700198773() throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        Method PDPageContentStreamWrite = PDPageContentStream.class.getSuperclass().getDeclaredMethod("write", String.class);
        PDPageContentStreamWrite.setAccessible(true);

        try (   InputStream resource = getClass().getResourceAsStream("4700198773.pdf"))
        {
            PDDocument document = Loader.loadPDF(resource);

            PDPage page = document.getPage(0);
            PDResources pageResources = page.getResources();
            COSName f1Name = COSName.getPDFName("F1");
            PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
            Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();

            COSDictionary charProcsDictionary = fontF1.getCharProcs();
            for (COSName key : charProcsDictionary.keySet())
            {
                COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
                PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
                PDRectangle bbox = charProc.getGlyphBBox();
                if (bbox == null)
                    bbox = charProc.getBBox();
                Integer code = f1NameToCode.get(key.getName());

                if (code != null)
                {
                    PDDocument charDocument = new PDDocument();
                    PDPage charPage = new PDPage(bbox);
                    charDocument.addPage(charPage);
                    charPage.setResources(pageResources);
                    PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
                    charContentStream.beginText();
                    charContentStream.setFont(fontF1, bbox.getHeight());
//                    charContentStream.write(String.format("<%2X> Tj\n", code).getBytes());
                    PDPageContentStreamWrite.invoke(charContentStream, String.format("<%2X> Tj\n", code));
                    charContentStream.endText();
                    charContentStream.close();

                    File result = new File(RESULT_FOLDER, String.format("4700198773-%s-%s.png", key.getName(), code));
                    PDFRenderer renderer = new PDFRenderer(charDocument);
                    BufferedImage image = renderer.renderImageWithDPI(0, 96);
                    ImageIO.write(image, "PNG", result);
                    charDocument.save(new File(RESULT_FOLDER, String.format("4700198773-%s-%s.pdf", key.getName(), code)));
                    charDocument.close();
                }
            }
        }
    }
 
Example 19
Source File: RenderType3Character.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
 * Render Type3 font character as image using PDFBox
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
 * 4700198773.pdf
 * </a>
 * from
 * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
 * extract text with custom font result non readble
 * </a>
 * <p>
 * This test shows how one can render individual Type 3 font glyphs as bitmaps.
 * Unfortunately PDFBox out-of-the-box does not provide a class to render contents
 * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
 * with the glyph in question and render that page.   
 * </p>
 * <p>
 * As the OP did not provide a sample PDF, we simply use one from another
 * stackoverflow question. There obviously might remain issues with the
 * OP's files.
 * </p>
 */
@Test
public void testRenderSdnList() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
{
    Method PDPageContentStreamWrite = PDPageContentStream.class.getSuperclass().getDeclaredMethod("write", String.class);
    PDPageContentStreamWrite.setAccessible(true);

    try (   InputStream resource = getClass().getResourceAsStream("sdnlist.pdf"))
    {
        PDDocument document = Loader.loadPDF(resource);

        PDPage page = document.getPage(1);
        PDResources pageResources = page.getResources();
        COSName f1Name = COSName.getPDFName("R144");
        PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
        Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();

        COSDictionary charProcsDictionary = fontF1.getCharProcs();
        for (COSName key : charProcsDictionary.keySet())
        {
            COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
            PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
            PDRectangle bbox = charProc.getGlyphBBox();
            if (bbox == null)
                bbox = charProc.getBBox();
            Integer code = f1NameToCode.get(key.getName());

            if (code != null)
            {
                PDDocument charDocument = new PDDocument();
                PDPage charPage = new PDPage(bbox);
                charDocument.addPage(charPage);
                charPage.setResources(pageResources);
                PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
                charContentStream.beginText();
                charContentStream.setFont(fontF1, bbox.getHeight());
                //charContentStream.getOutputStream().write(String.format("<%2X> Tj\n", code).getBytes());
                PDPageContentStreamWrite.invoke(charContentStream, String.format("<%2X> Tj\n", code));
                charContentStream.endText();
                charContentStream.close();

                File result = new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.png", key.getName(), code));
                PDFRenderer renderer = new PDFRenderer(charDocument);
                BufferedImage image = renderer.renderImageWithDPI(0, 96);
                ImageIO.write(image, "PNG", result);
                charDocument.save(new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.pdf", key.getName(), code)));
                charDocument.close();
            }
        }
    }
}
 
Example 20
Source File: TextAndGraphics.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/44503236/how-to-write-text-draw-a-line-and-then-again-write-text-in-a-pdf-file-using-pdf">
 * How to write text, draw a line and then again write text in a pdf file using PDFBox
 * </a>
 * <p>
 * This test shows how to draw tetx, then graphics, then again text.
 * </p>
 */
@Test
public void testDrawTextLineText() throws IOException
{
    PDFont font = PDType1Font.HELVETICA;
    float fontSize = 14;
    float fontHeight = fontSize;
    float leading = 20;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
    Date date = new Date();

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);

    PDPageContentStream contentStream = new PDPageContentStream(doc, page);
    contentStream.setFont(font, fontSize);

    float yCordinate = page.getCropBox().getUpperRightY() - 30;
    float startX = page.getCropBox().getLowerLeftX() + 30;
    float endX = page.getCropBox().getUpperRightX() - 30;

    contentStream.beginText();
    contentStream.newLineAtOffset(startX, yCordinate);
    contentStream.showText("Entry Form � Header");
    yCordinate -= fontHeight;  //This line is to track the yCordinate
    contentStream.newLineAtOffset(0, -leading);
    yCordinate -= leading;
    contentStream.showText("Date Generated: " + dateFormat.format(date));
    yCordinate -= fontHeight;
    contentStream.endText(); // End of text mode

    contentStream.moveTo(startX, yCordinate);
    contentStream.lineTo(endX, yCordinate);
    contentStream.stroke();
    yCordinate -= leading;

    contentStream.beginText();
    contentStream.newLineAtOffset(startX, yCordinate);
    contentStream.showText("Name: XXXXX");
    contentStream.endText();

    contentStream.close();
    doc.save(new File(RESULT_FOLDER, "textLineText.pdf"));
}