List of usage examples for org.apache.pdfbox.pdmodel PDDocument save
public void save(OutputStream output) throws IOException
From source file:com.ackpdfbox.app.Encrypt.java
License:Apache License
private void encrypt(String[] args) throws IOException, CertificateException { if (args.length < 1) { usage();//from w w w . ja va 2 s . co m } else { AccessPermission ap = new AccessPermission(); String infile = null; String outfile = null; String certFile = null; String userPassword = ""; String ownerPassword = ""; int keyLength = 40; PDDocument document = null; try { for (int i = 0; i < args.length; i++) { String key = args[i]; if (key.equals("-O")) { ownerPassword = args[++i]; } else if (key.equals("-U")) { userPassword = args[++i]; } else if (key.equals("-canAssemble")) { ap.setCanAssembleDocument(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-canExtractContent")) { ap.setCanExtractContent(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-canExtractForAccessibility")) { ap.setCanExtractForAccessibility(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-canFillInForm")) { ap.setCanFillInForm(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-canModify")) { ap.setCanModify(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-canModifyAnnotations")) { ap.setCanModifyAnnotations(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-canPrint")) { ap.setCanPrint(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-canPrintDegraded")) { ap.setCanPrintDegraded(args[++i].equalsIgnoreCase("true")); } else if (key.equals("-certFile")) { certFile = args[++i]; } else if (key.equals("-keyLength")) { try { keyLength = Integer.parseInt(args[++i]); } catch (NumberFormatException e) { throw new NumberFormatException( "Error: -keyLength is not an integer '" + args[i] + "'"); } } else if (infile == null) { infile = key; } else if (outfile == null) { outfile = key; } else { usage(); } } if (infile == null) { usage(); } if (outfile == null) { outfile = infile; } document = PDDocument.load(new File(infile)); if (!document.isEncrypted()) { if (certFile != null) { PublicKeyProtectionPolicy ppp = new PublicKeyProtectionPolicy(); PublicKeyRecipient recip = new PublicKeyRecipient(); recip.setPermission(ap); CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream inStream = null; try { inStream = new FileInputStream(certFile); X509Certificate certificate = (X509Certificate) cf.generateCertificate(inStream); recip.setX509(certificate); } finally { if (inStream != null) { inStream.close(); } } ppp.addRecipient(recip); ppp.setEncryptionKeyLength(keyLength); document.protect(ppp); } else { StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, userPassword, ap); spp.setEncryptionKeyLength(keyLength); document.protect(spp); } document.save(outfile); } else { System.err.println("Error: Document is already encrypted."); } } finally { if (document != null) { document.close(); } } } }
From source file:com.encodata.PDFSigner.PDFSigner.java
public void createPDFFromImage(String inputFile, String imagePath, String outputFile, String x, String y, String width, String height, CallbackContext callbackContext) throws IOException { if (inputFile == null || imagePath == null || outputFile == null) { callbackContext.error("Expected localFile and remoteFile."); } else {/*from ww w.ja v a 2s.c om*/ // the document PDDocument doc = null; try { doc = PDDocument.load(new File(inputFile)); //we will add the image to the first page. PDPage page = doc.getPage(0); // createFromFile is the easiest way with an image file // if you already have the image in a BufferedImage, // call LosslessFactory.createFromImage() instead PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc); PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 // reduce this value if the image is too large float scale = 1f; contentStream.drawImage(pdImage, Float.parseFloat(x), Float.parseFloat(y), Float.parseFloat(width) * scale, Float.parseFloat(height) * scale); contentStream.close(); doc.save(outputFile); callbackContext.success(outputFile); } catch (Exception e) { callbackContext.error(e.toString()); } finally { if (doc != null) { doc.close(); } } } }
From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java
License:Open Source License
/** * Prints the current page to a pdf file * * @throws IOException if the file cannot be found or the pdf cannot be created *//*from w w w. j a va 2 s .c om*/ protected void printCurrentPageToPdf() throws IOException { io.clearActivePoints(); ddf.updateAll(io.getActivePoints()); String fileName = DBMenuBar.cleanseFileName( Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6) + ": " + Main.getCurrentPage().toDisplayString().replaceAll("\\|", "-")); File f = new File(Main.getFilePath()); f.mkdirs(); f = new File(Main.getFilePath() + fileName + ".pdf"); BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paintComponent(g); g.dispose(); PDDocument doc = null; try { doc = new PDDocument(); boolean crop = true; State.print(field); for (Point p : Main.getCurrentPage().getDots().keySet()) if (p.getX() < field.getWidth() * 0.1 + field.getX() || p.getX() > field.getWidth() * 0.9 + field.getX()) { crop = false; break; } if (Main.getCurrentPage().getTextPoint().getX() < field.getWidth() * 0.1 + field.getX() || Main.getCurrentPage().getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX()) crop = false; float scale = 1.0f; if (crop) scale = 0.8f; PDPage page = new PDPage(new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight())); doc.addPage(page); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi); PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true); contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()), -1 * field.y, pdImage.getWidth(), pdImage.getHeight()); contentStream.close(); doc.save(f); } finally { if (doc != null) doc.close(); } }
From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java
License:Open Source License
/** * Prints every page to a pdf file// ww w. j av a2s .c om * * @throws IOException if the file cannot be found or the pdf cannot be created */ protected void printAllPagesToPdf() throws IOException { io.clearActivePoints(); ddf.updateAll(io.getActivePoints()); File f = new File(Main.getFilePath()); f.mkdirs(); String fileName = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)); f = new File(Main.getFilePath() + fileName + " full show" + ".pdf"); boolean crop = true; a: for (int pageNum : Main.getPages().keySet()) { for (Point p : Main.getPages().get(pageNum).getDots().keySet()) { if (p.getX() < field.getWidth() * 0.1 + field.getX() || p.getX() > field.getWidth() * 0.9 + field.getX()) { crop = false; break a; } } if (Main.getPages().get(pageNum).getTextPoint().getX() < field.getWidth() * 0.1 + field.getX() || Main.getPages().get(pageNum).getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX()) { crop = false; break; } } float scale = 1.0f; if (crop) scale = 0.8f; PDDocument doc = null; try { doc = new PDDocument(); for (int i : Main.getPages().keySet()) { Main.setCurrentPage(i); BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); paintComponent(g); g.dispose(); PDPage page = new PDPage( new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight())); doc.addPage(page); PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi); PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true); contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()), -1 * field.y, pdImage.getWidth(), pdImage.getHeight()); contentStream.close(); } doc.save(f); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); pdf.updateAfterPrintAll(); } }
From source file:com.evanbelcher.DrillBook.DotSheetMaker.java
License:Open Source License
/** * Prints all dot sheets to pdf files/*from w ww. j a va2 s .c o m*/ */ private void printAllToPdf() throws IOException { printing = true; String folder = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)) + " Dot Sheets/"; File f = new File(Main.getFilePath() + folder); f.mkdirs(); PDDocument doc = null; String[] chars = new String[26]; for (int i = 0; i < 26; i++) chars[i] = String.valueOf((char) (65 + i)); try { for (String letter : chars) { doc = new PDDocument(); String fileName = Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6) + " " + DBMenuBar.cleanseFileName(letter); f = new File(Main.getFilePath() + folder + fileName + " dot sheet.pdf"); ArrayList<String> list = new ArrayList<>(map.keySet()); list.sort(nameComparator); for (String dotName : list) { if (dotName.replaceAll("[0-9]", "").equals(letter)) { int i = 0; PDPage page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.HELVETICA_BOLD; PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.beginText(); contentStream.setFont(font, 10.0f); contentStream.newLineAtOffset(10, page.getMediaBox().getHeight() - 20); contentStream.showText(Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.3f, page.getMediaBox().getHeight() - 20); contentStream.showText(dotName); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 10.0f); contentStream.newLineAtOffset(page.getMediaBox().getWidth() * 0.6f, page.getMediaBox().getHeight() - 20); contentStream.showText("Name: ______________________________"); contentStream.endText(); contentStream.close(); float margin = 10; float tableWidth = page.getMediaBox().getWidth() - (2 * margin); float yStartNewPage = page.getMediaBox().getHeight() - (3 * margin); //noinspection UnnecessaryLocalVariable float yStart = yStartNewPage; float bottomMargin = 70; BaseTable table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, true); //Create Header row Row<PDPage> headerRow = table.createRow(15f); Cell<PDPage> headerCell = headerRow.createCell(100 / 7f, "Set #"); headerCell.setAlign(HorizontalAlignment.CENTER); headerCell.setFillColor(HEADER_COLOR); headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell); headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell); table.addHeaderRow(headerRow); for (int pageNum : new TreeSet<>(map.get(dotName).keySet())) { String text = map.get(dotName).get(pageNum); String[] lines = text.split("\\n"); String line1 = lines[0].replace("Horizontal - ", ""); String line2 = lines[1].replace("Vertical - ", ""); Row<PDPage> row = table.createRow(10f); Cell<PDPage> cell = row.createCell(100 / 7f, pageNum + ""); cell.setAlign(HorizontalAlignment.CENTER); cell.setFillColor(openingSets.contains(pageNum) ? OPENING_SET_COLOR : NORMAL_COLOR); row.createCell(300 / 7f, line1).copyCellStyle(cell); row.createCell(300 / 7f, line2).copyCellStyle(cell); if (++i >= 35) { table.draw(); page = new PDPage(); doc.addPage(page); table = new BaseTable(yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, true); //Create Header row headerRow = table.createRow(15f); headerCell = headerRow.createCell(100 / 7f, "Set #"); headerCell.setAlign(HorizontalAlignment.CENTER); headerCell.setFillColor(HEADER_COLOR); headerRow.createCell(300 / 7f, "Horizontal").copyCellStyle(headerCell); headerRow.createCell(300 / 7f, "Vertical").copyCellStyle(headerCell); table.addHeaderRow(headerRow); i -= 35; } } table.draw(); } } if (doc.getNumberOfPages() > 0) doc.save(f); else doc.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (doc != null) doc.close(); } printing = false; }
From source file:com.fangxin365.core.utils.PDFMerger.java
License:Apache License
/** * Merge the list of source documents, saving the result in the destination * file.//from w w w. ja v a 2 s . c om * * @throws IOException * If there is an error saving the document. * @throws COSVisitorException * If an error occurs while saving the destination file. */ public void mergeDocuments() throws IOException, COSVisitorException { PDDocument destination = null; InputStream sourceFile; PDDocument source; if (sources != null && sources.size() > 0) { java.util.Vector<PDDocument> tobeclosed = new java.util.Vector<PDDocument>(); try { Iterator<InputStream> sit = sources.iterator(); sourceFile = sit.next(); destination = PDDocument.load(sourceFile); while (sit.hasNext()) { sourceFile = sit.next(); source = PDDocument.load(sourceFile); tobeclosed.add(source); appendDocument(destination, source); } if (destinationStream == null) { destination.save(destinationFileName); } else { destination.save(destinationStream); } } finally { if (destination != null) { destination.close(); } for (PDDocument doc : tobeclosed) { doc.close(); } } } }
From source file:com.fileOperations.EmailBodyToPDF.java
/** * Places the text of the email into the PDF * * @param eml EmailBodyPDF//from ww w. j av a 2 s . com */ private static void createEmailBody(EmailBodyPDF eml) { PDDocument doc = null; PDPageContentStream contentStream = null; //Fonts used PDFont bodyTitleFont = PDType1Font.TIMES_BOLD; PDFont bodyFont = PDType1Font.TIMES_ROMAN; //Font Sizes float emailHeaderFontSize = 7; float leadingEmailHeader = 1.5f * emailHeaderFontSize; 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 List<String> sentDateContent = PDFBoxTools.setLineBreaks(eml.getSentDate(), width, emailHeaderFontSize, bodyFont); List<String> recievedDateContent = PDFBoxTools.setLineBreaks(eml.getReceiveDate(), width, emailHeaderFontSize, bodyFont); List<String> toContent = PDFBoxTools.setLineBreaks(eml.getTo(), width, emailHeaderFontSize, bodyFont); List<String> fromContent = PDFBoxTools.setLineBreaks(eml.getFrom(), width, emailHeaderFontSize, bodyFont); List<String> ccContent = PDFBoxTools.setLineBreaks(eml.getCc(), width, emailHeaderFontSize, bodyFont); List<String> bccContent = PDFBoxTools.setLineBreaks(eml.getBcc(), width, emailHeaderFontSize, bodyFont); List<String> attachmentContent = PDFBoxTools.setLineBreaks(eml.getAttachments(), width, emailHeaderFontSize, bodyFont); List<String> subjectContent = PDFBoxTools.setLineBreaks(eml.getSubject(), width, bodyFontSize, bodyFont); List<String> bodyContent = PDFBoxTools.setLineBreaks(eml.getBody(), width, bodyFontSize, bodyFont); //Set Email Header contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); //Set Date Sent if (!"".equals(eml.getSentDate())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("Date Sent: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : sentDateContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set Date Received if (!"".equals(eml.getReceiveDate().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("Date Received: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : recievedDateContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingBody; } } contentStream.newLineAtOffset(0, -leadingBody); //Set From if (!"".equals(eml.getFrom().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("From: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : fromContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set To if (!"".equals(eml.getTo().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("To: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : toContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set CC if (!"".equals(eml.getCc().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("CC: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : ccContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set BCC if (!"".equals(eml.getBcc().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("BCC: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : bccContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set AttachmentList if (!"".equals(eml.getAttachments().trim())) { contentStream.setFont(bodyTitleFont, emailHeaderFontSize); contentStream.showText("Attachments: "); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; for (String line : attachmentContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingEmailHeader); textYlocation += leadingEmailHeader; } } //Set Subject if (!"".equals(eml.getSubject().trim())) { contentStream.newLineAtOffset(0, -leadingBody); contentStream.newLineAtOffset(0, -leadingBody); contentStream.setFont(bodyTitleFont, bodyFontSize); contentStream.showText("Subject: "); contentStream.newLineAtOffset(0, -leadingBody); textYlocation += leadingBody; contentStream.setFont(bodyFont, bodyFontSize); for (String line : subjectContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingEmailHeader)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, false); contentStream.beginText(); contentStream.setFont(bodyFont, emailHeaderFontSize); contentStream.setNonStrokingColor(Color.BLACK); contentStream.newLineAtOffset(startX, startY); } contentStream.showText(line); contentStream.newLineAtOffset(0, -leadingBody); textYlocation += leadingBody; } } if (!"".equals(eml.getBody().trim())) { // Set Email Body contentStream.newLineAtOffset(0, -leadingBody); contentStream.setFont(bodyTitleFont, bodyFontSize); contentStream.showText("Message: "); contentStream.setFont(bodyFont, bodyFontSize); contentStream.newLineAtOffset(0, -leadingBody); for (String line : bodyContent) { if (textYlocation > (mediabox.getHeight() - (margin * 2) - leadingBody)) { contentStream.endText(); contentStream.close(); textYlocation = 0; page = new PDPage(); doc.addPage(page); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, 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(eml.getFilePath() + eml.getFileName()); } catch (IOException ex) { ExceptionHandler.Handle(ex); } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); } } } }
From source file:com.fileOperations.ImageToPDF.java
/** * create PDF from image and scales it accordingly to fit in a single page * * @param folderPath String/*from ww w. ja va 2s. c om*/ * @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/*from w ww . j a v a 2 s .c o m*/ * @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.StampPDF.java
/** * This stamps docketed files./*ww w.j a v a2s . c o m*/ * * @param file String (full file path) * @param docketTime Timestamp * @param dept */ public static void stampDocument(String file, Timestamp docketTime, String dept) { // the document PDDocument doc = null; try { PDFont stampFont = PDType1Font.TIMES_ROMAN; float stampFontSize = 14; String title = PDFBoxTools.HeaderTimeStamp(docketTime) + " " + dept; float titleWidth = stampFont.getStringWidth(title) / 1000 * stampFontSize; float titleHeight = stampFont.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * stampFontSize; int marginTop = 20; doc = PDDocument.load(new File(file)); if (!doc.isEncrypted()) { for (int i = 0; i < doc.getPages().getCount(); i++) { PDPageContentStream contentStream = null; PDPage page = (PDPage) doc.getPages().get(i); contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true); page.getResources().getFontNames(); contentStream.beginText(); contentStream.setFont(stampFont, stampFontSize); contentStream.setNonStrokingColor(Color.RED); contentStream.newLineAtOffset((page.getMediaBox().getWidth() - titleWidth) / 2, page.getMediaBox().getHeight() - marginTop - titleHeight); contentStream.showText(title); contentStream.endText(); contentStream.close(); } doc.save(file); } } catch (IOException ex) { ExceptionHandler.Handle(ex); } finally { if (doc != null) { try { doc.close(); } catch (IOException ex) { ExceptionHandler.Handle(ex); } } } }