List of usage examples for org.apache.pdfbox.pdmodel PDDocument addPage
public void addPage(PDPage page)
From source file:com.fileOperations.ImageToPDF.java
/** * create PDF from image and scales it accordingly to fit in a single page * * @param folderPath String/* w w w. ja v a2s . c o m*/ * @param imageFileName String * @return String new filename */ public static String createPDFFromImage(String folderPath, String imageFileName) { String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf"; String image = folderPath + imageFileName; PDImageXObject pdImage = null; File imageFile = null; FileInputStream fileStream = null; BufferedImage bim = null; File attachmentLocation = new File(folderPath); if (!attachmentLocation.exists()) { attachmentLocation.mkdirs(); } // the document PDDocument doc = null; PDPageContentStream contentStream = null; try { doc = new PDDocument(); PDPage page = new PDPage(PDRectangle.LETTER); float margin = 72; float pageWidth = page.getMediaBox().getWidth() - 2 * margin; float pageHeight = page.getMediaBox().getHeight() - 2 * margin; if (image.toLowerCase().endsWith(".jpg")) { imageFile = new File(image); fileStream = new FileInputStream(image); pdImage = JPEGFactory.createFromStream(doc, fileStream); // } else if ((image.toLowerCase().endsWith(".tif") // || image.toLowerCase().endsWith(".tiff")) // && TIFFCompression(image) == COMPRESSION_GROUP4) { // imageFile = new File(image); // pdImage = CCITTFactory.createFromFile(doc, imageFile); } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp") || image.toLowerCase().endsWith(".png")) { imageFile = new File(image); bim = ImageIO.read(imageFile); pdImage = LosslessFactory.createFromImage(doc, bim); } if (pdImage != null) { if (pdImage.getWidth() > pdImage.getHeight()) { page.setRotation(270); PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(), page.getMediaBox().getWidth()); page.setMediaBox(rotatedPage); pageWidth = page.getMediaBox().getWidth() - 2 * margin; pageHeight = page.getMediaBox().getHeight() - 2 * margin; } Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight); Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight()); Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize); float startX = page.getMediaBox().getLowerLeftX() + margin; float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height; doc.addPage(page); contentStream = new PDPageContentStream(doc, page); contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height); contentStream.close(); doc.save(folderPath + pdfFile); } } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } } if (fileStream != null) { try { fileStream.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } if (bim != null) { bim.flush(); } if (imageFile != null) { imageFile.delete(); } return pdfFile; }
From source file:com.fileOperations.ImageToPDF.java
/** * create PDF from image and scales it accordingly to fit in a single page * * @param folderPath String/*w ww .j av a 2 s .com*/ * @param imageFileName String * @return String new filename */ public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) { String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf"; String image = folderPath + imageFileName; PDImageXObject pdImage = null; File imageFile = null; FileInputStream fileStream = null; BufferedImage bim = null; File attachmentLocation = new File(folderPath); if (!attachmentLocation.exists()) { attachmentLocation.mkdirs(); } // the document PDDocument doc = null; PDPageContentStream contentStream = null; try { doc = new PDDocument(); PDPage page = new PDPage(PDRectangle.LETTER); float margin = 72; float pageWidth = page.getMediaBox().getWidth() - 2 * margin; float pageHeight = page.getMediaBox().getHeight() - 2 * margin; if (image.toLowerCase().endsWith(".jpg")) { imageFile = new File(image); fileStream = new FileInputStream(image); pdImage = JPEGFactory.createFromStream(doc, fileStream); // } else if ((image.toLowerCase().endsWith(".tif") // || image.toLowerCase().endsWith(".tiff")) // && TIFFCompression(image) == COMPRESSION_GROUP4) { // imageFile = new File(image); // pdImage = CCITTFactory.createFromFile(doc, imageFile); } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp") || image.toLowerCase().endsWith(".png")) { imageFile = new File(image); bim = ImageIO.read(imageFile); pdImage = LosslessFactory.createFromImage(doc, bim); } if (pdImage != null) { if (pdImage.getWidth() > pdImage.getHeight()) { page.setRotation(270); PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(), page.getMediaBox().getWidth()); page.setMediaBox(rotatedPage); pageWidth = page.getMediaBox().getWidth() - 2 * margin; pageHeight = page.getMediaBox().getHeight() - 2 * margin; } Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight); Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight()); Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize); float startX = page.getMediaBox().getLowerLeftX() + margin; float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height; doc.addPage(page); contentStream = new PDPageContentStream(doc, page); contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height); contentStream.close(); doc.save(folderPath + pdfFile); } } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } } if (fileStream != null) { try { fileStream.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); return ""; } } if (bim != null) { bim.flush(); } return pdfFile; }
From source file:com.fileOperations.TXTtoPDF.java
/** * Takes the text from the string and insert it into the PDF file * * @param pdfFile String (path + filename) * @param text String (text from document) *//* ww w . ja v a 2 s . co m*/ private static void makePDF(String pdfFile, String text) { PDDocument doc = null; PDPageContentStream contentStream = null; //Fonts used PDFont bodyFont = PDType1Font.TIMES_ROMAN; //Font Sizes float bodyFontSize = 12; float leadingBody = 1.5f * bodyFontSize; try { //Create Document, Page, Margins. doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); PDRectangle mediabox = page.getMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; float textYlocation = margin; //Set Line Breaks text = text.replaceAll("[\\p{C}\\p{Z}]", System.getProperty("line.separator")); //strip ZERO WIDTH SPACE List<String> textContent = PDFBoxTools.setLineBreaks(text, width, bodyFontSize, bodyFont); contentStream.beginText(); contentStream.setFont(bodyFont, bodyFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); if (!"".equals(text)) { for (String line : textContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, true, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, bodyFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } textYlocation += leadingBody; contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingBody); } contentStream.endText(); } contentStream.close(); doc.save(pdfFile); } catch (IOException ex) { ExceptionHandler.Handle(ex); } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:com.foc.vaadin.gui.pdfGenerator.FocXmlPDFParser.java
License:Apache License
public void createDocument() { PDDocument document = getPDDocument(); PDPage page = getPDPage(); document.addPage(page); }
From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java
License:Open Source License
private static void initNewPage(PDDocument doc) { positionHeight = DEFAULT_MARGIN_HEIGHT; positionLogoWidth = DEFAULT_ICON_MARGIN_WIDTH; positionTitleWidth = DEFAULT_TITLE_MARGIN_WIDTH; page = new PDPage(); doc.addPage(page); }
From source file:com.helger.pdflayout.element.PLPageSet.java
License:Apache License
/** * Render all pages of this layout to the specified PDDocument * * @param aPrepareResult/*from ww w . j a va 2 s. c o m*/ * The preparation result. May not be <code>null</code>. * @param aDoc * The PDDocument. May not be <code>null</code>. * @param bDebug * <code>true</code> for debug output * @param nPageSetIndex * Page set index. Always ≥ 0. * @param nTotalPageStartIndex * Total page index. Always ≥ 0. * @param nTotalPageCount * Total page count. Always ≥ 0. * @throws IOException * In case of render errors */ public void renderAllPages(@Nonnull final PageSetPrepareResult aPrepareResult, @Nonnull final PDDocument aDoc, final boolean bDebug, @Nonnegative final int nPageSetIndex, @Nonnegative final int nTotalPageStartIndex, @Nonnegative final int nTotalPageCount) throws IOException { // Start at the left final float fXLeft = getMarginLeft() + getPaddingLeft(); final float fYTop = getYTop(); final boolean bCompressPDF = !bDebug; int nPageIndex = 0; final int nPageCount = aPrepareResult.getPageCount(); for (final List<PLElementWithSize> aPerPage : aPrepareResult.directGetPerPageElements()) { if (PLDebug.isDebugRender()) PLDebug.debugRender(this, "Start rendering page index " + nPageIndex + " (" + (nTotalPageStartIndex + nPageIndex) + ") with page size " + getPageWidth() + " & " + getPageHeight() + " and available size " + getAvailableWidth() + " & " + getAvailableHeight()); final RenderPageIndex aPageIndex = new RenderPageIndex(nPageSetIndex, nPageIndex, nPageCount, nTotalPageStartIndex + nPageIndex, nTotalPageCount); // Layout in memory final PDPage aPage = new PDPage(m_aPageSize.getAsRectangle()); aDoc.addPage(aPage); { final PageSetupContext aCtx = new PageSetupContext(aDoc, aPage); if (m_aPageHeader != null) m_aPageHeader.doPageSetup(aCtx); for (final PLElementWithSize aElement : aPerPage) aElement.getElement().doPageSetup(aCtx); if (m_aPageFooter != null) m_aPageFooter.doPageSetup(aCtx); } final PDPageContentStreamWithCache aContentStream = new PDPageContentStreamWithCache(aDoc, aPage, false, bCompressPDF); try { // Page rect before content - debug: red { final float fLeft = getMarginLeft(); final float fTop = m_aPageSize.getHeight() - getMarginTop(); final float fWidth = m_aPageSize.getWidth() - getMarginXSum(); final float fHeight = m_aPageSize.getHeight() - getMarginYSum(); // Fill before border if (getFillColor() != null) { aContentStream.setNonStrokingColor(getFillColor()); aContentStream.fillRect(fLeft, fTop - fHeight, fWidth, fHeight); } BorderSpec aRealBorder = getBorder(); if (shouldApplyDebugBorder(aRealBorder, bDebug)) aRealBorder = new BorderSpec(new BorderStyleSpec(PLDebug.BORDER_COLOR_PAGESET)); if (aRealBorder.hasAnyBorder()) renderBorder(aContentStream, fLeft, fTop, fWidth, fHeight, aRealBorder); } // Start with the page rect if (m_aPageHeader != null) { // Page header does not care about page padding // header top-left final RenderingContext aRC = new RenderingContext(ERenderingElementType.PAGE_HEADER, aContentStream, bDebug, getMarginLeft() + m_aPageHeader.getMarginLeft(), m_aPageSize.getHeight() - m_aPageHeader.getMarginTop(), m_aPageSize.getWidth() - getMarginXSum() - m_aPageHeader.getMarginXSum(), aPrepareResult.getHeaderHeight() + m_aPageHeader.getPaddingYSum()); aPageIndex.setPlaceholdersInRenderingContext(aRC); if (m_aRCCustomizer != null) m_aRCCustomizer.customizeRenderingContext(aRC); m_aPageHeader.perform(aRC); } float fCurY = fYTop; for (final PLElementWithSize aElementWithHeight : aPerPage) { final AbstractPLElement<?> aElement = aElementWithHeight.getElement(); // Get element height final float fThisHeight = aElementWithHeight.getHeight(); final float fThisHeightWithPadding = fThisHeight + aElement.getPaddingYSum(); final RenderingContext aRC = new RenderingContext(ERenderingElementType.CONTENT_ELEMENT, aContentStream, bDebug, fXLeft + aElement.getMarginLeft(), fCurY - aElement.getMarginTop(), getAvailableWidth() - aElement.getMarginXSum(), fThisHeightWithPadding); aPageIndex.setPlaceholdersInRenderingContext(aRC); if (m_aRCCustomizer != null) m_aRCCustomizer.customizeRenderingContext(aRC); aElement.perform(aRC); fCurY -= fThisHeightWithPadding + aElement.getMarginYSum(); } if (m_aPageFooter != null) { // Page footer does not care about page padding // footer top-left final float fStartLeft = getMarginLeft() + m_aPageFooter.getMarginLeft(); final float fStartTop = getMarginBottom() - m_aPageFooter.getMarginTop(); final float fWidth = m_aPageSize.getWidth() - getMarginXSum() - m_aPageFooter.getMarginXSum(); final float fHeight = aPrepareResult.getFooterHeight() + m_aPageFooter.getPaddingYSum(); final RenderingContext aRC = new RenderingContext(ERenderingElementType.PAGE_FOOTER, aContentStream, bDebug, fStartLeft, fStartTop, fWidth, fHeight); aPageIndex.setPlaceholdersInRenderingContext(aRC); if (m_aRCCustomizer != null) m_aRCCustomizer.customizeRenderingContext(aRC); m_aPageFooter.perform(aRC); } } finally { aContentStream.close(); } ++nPageIndex; } if (PLDebug.isDebugRender()) PLDebug.debugRender(this, "Finished rendering"); }
From source file:com.hostandguest.services.FXML_BookingListController.java
private boolean saveToPDF(Booking booking) { try {//from w w w .j a v a 2 s . co m // get the user to provide save directory DirectoryChooser directoryChooser = new DirectoryChooser(); directoryChooser.setTitle("Choose Save Location"); File selectedDir = directoryChooser.showDialog(new Stage()); String fileName = booking.getGuest().getLast_name() + " " + booking.getGuest().getFirst_name() + " " + booking.getBookingDate().toString() + ".pdf"; PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream content = new PDPageContentStream(doc, page); // setting content content.beginText(); content.setFont(PDType1Font.HELVETICA, 26); content.newLineAtOffset(220, 750); content.showText("Reservation Form"); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 700); content.showText("Name : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 700); content.showText(booking.getGuest().getLast_name() + " " + booking.getGuest().getFirst_name()); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 650); content.showText("Reservation Date : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 650); content.showText(booking.getBookingDate().toString()); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 600); content.showText("Term : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 600); content.showText(String.valueOf(booking.getTerm())); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 550); content.showText("Number of Rooms : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 550); content.showText(String.valueOf(booking.getNbr_rooms_reserved())); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 500); content.showText("Total Amount : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 500); content.showText(String.valueOf(booking.getTotal_amount())); content.endText(); // content.close(); doc.save(selectedDir.getAbsolutePath() + "\\" + fileName); doc.close(); return true; } catch (IOException ex) { Logger.getLogger(FXML_BookingListController.class.getName()).log(Level.SEVERE, null, ex); } return false; }
From source file:com.jaromin.alfresco.repo.content.transform.CorelDrawContentTransformer.java
License:Apache License
/** * /* ww w . jav a2 s .c om*/ * @param pageImages * @param out * @throws IOException * @throws FileNotFoundException * @throws COSVisitorException */ private void buildPdfFromImages(Map<File, Dimension> pageImages, OutputStream out) throws IOException, FileNotFoundException, COSVisitorException { PDDocument doc = new PDDocument(); for (Map.Entry<File, Dimension> entry : pageImages.entrySet()) { File pFile = entry.getKey(); Dimension d = entry.getValue(); PDRectangle size = new PDRectangle(d.width, d.height); PDPage page = new PDPage(size); doc.addPage(page); PDXObjectImage ximage = new PDJpeg(doc, new FileInputStream(pFile)); PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.drawImage(ximage, size.getLowerLeftX(), size.getLowerLeftY()); contentStream.close(); } doc.save(out); }
From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java
License:Open Source License
/** * create the second sample document from the PDF file format specification. * @param reportDataMap //from www .j a va 2s.co m * * @param file The file to write the PDF to. * @param message The message to write in the file. * * @throws IOException If there is an error writing the data. * @throws COSVisitorException If there is an error writing the PDF. */ public String createMetricReport(Map<String, String> reportDataMap) throws IOException, COSVisitorException { // the document PDDocument doc = null; StringBuilder strRow = new StringBuilder(); String reportname = null; java.util.Random R = new java.util.Random(); try { doc = new PDDocument(); System.out.println("Creating PDF Line 264"); PDPage page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.HELVETICA_BOLD; PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700 - 0); contentStream.drawString(" Sonar Analysis Report "); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700 - 20); contentStream.drawString("==================================================== "); contentStream.endText(); System.out.println("Print Entries from Analysis Data Map."); int i = 2; for (Map.Entry<String, String> entry : reportDataMap.entrySet()) { contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700 - (i * 20)); contentStream.drawString(i + ") " + entry.getKey() + " = " + entry.getValue()); contentStream.endText(); //strRow.append(i + ") " + entry.getKey() + " = " + entry.getValue() + "\n "); i++; } //System.out.println(strRow); contentStream.close(); System.out.println("Done Writing Text.Save Doc."); reportname = "sonarreport" + java.util.Calendar.getInstance().getTimeInMillis() + "_" + R.nextInt() + ".pdf"; doc.save(reportname); System.out.println("Report Created.Exit to email sending. name=>" + reportname); } finally { if (doc != null) { doc.close(); } } return reportname; }
From source file:com.mycompany.mavenproject4.NewMain.java
/** * @param args the command line arguments *//* w ww.j ava2s . c o m*/ public static void main(String[] args) { PDDocument doc; doc = new PDDocument(); doc.addPage(new PDPage()); try { doc.save("Empty PDF.pdf"); doc.close(); } catch (Exception io) { System.out.println(io); } }