Java Code Examples for org.apache.pdfbox.pdmodel.edit.PDPageContentStream#close()

The following examples show how to use org.apache.pdfbox.pdmodel.edit.PDPageContentStream#close() . 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: Settings.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String checkPDFTemplateFileName(String PDFTemplateFileName, String path) throws IOException, IllegalArgumentException {
	String template;
	if (PDFTemplateFileName != null && PDFTemplateFileName.length() > 0) {
		File file = new File(PDFTemplateFileName);
		if (file.exists()) {
			if (file.isFile()) {
				if (file.canRead()) {
					PDDocument doc = null;
					try {
						doc = PDDocument.load(file);
						PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0);
						PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
						contentStream.close();
						template = file.getCanonicalPath();
					} catch (Exception e) {
						throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_INVALID_PDF_ERROR,
								DefaultMessages.PDF_TEMPLATE_FILE_INVALID_PDF_ERROR, PDFTemplateFileName), e);
					} finally {
						if (doc != null) {
							doc.close();
						}
					}
				} else {
					throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_ACCESS_ERROR, DefaultMessages.PDF_TEMPLATE_FILE_ACCESS_ERROR,
							PDFTemplateFileName));
				}
			} else {
				throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_NOTAFILE_ERROR, DefaultMessages.PDF_TEMPLATE_FILE_NOTAFILE_ERROR,
						PDFTemplateFileName));
			}
		} else {
			throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.PDF_TEMPLATE_FILE_DOES_NOT_EXIST_ERROR, DefaultMessages.PDF_TEMPLATE_FILE_DOES_NOT_EXIST_ERROR,
					PDFTemplateFileName));
		}
	} else {
		template = "";
	}
	return template;
}
 
Example 2
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 3
Source File: PdfBoxPDFWatermarkWriter.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
private void internalWriteWatermark(Watermark watermark) throws IOException {
	setWatermark(watermark);
	createPDFLines();
	List allPages = document.getDocumentCatalog().getAllPages();
	boolean alternateWatermark = false;
	if (getPageLayout() == PageLayout.A5) {
		alternateWatermark = true;
	}
	boolean leftPage = true;
	for (int i = 0; i < allPages.size(); i++) {
		PDPage page = (PDPage) allPages.get(i);
		PDRectangle mediaBox = page.findMediaBox();
		
		PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);
		if (alternateWatermark) {
			if (leftPage) {
				writeColumn1Line1(contentStream, page, mediaBox);
				writeColumn1Line2(contentStream, page, mediaBox);
			} else {
				writeColumn2Line1(contentStream, page, mediaBox);
				writeColumn2Line2(contentStream, page, mediaBox);
			}
		} else {
			writeColumn1Line1(contentStream, page, mediaBox);
			writeColumn1Line2(contentStream, page, mediaBox);
			writeColumn2Line1(contentStream, page, mediaBox);
			writeColumn2Line2(contentStream, page, mediaBox);
		}
		contentStream.close();
		leftPage = !leftPage;
	}
}
 
Example 4
Source File: ReportConvertPdf.java    From yuzhouwan with Apache License 2.0 4 votes vote down vote up
private static void finish(String pdfPath, PDDocument doc, PDPageContentStream content)
        throws IOException, COSVisitorException {
    content.close();
    doc.save(pdfPath);
    doc.close();
}
 
Example 5
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());

}