public static void main(String[] args) throws IOException { try (PDDocument doc = new PDDocument()) { PDPage page = new PDPage(); // Create a landscape page // page.setMediaBox(new PDRectangle(PDRectangle.A4.getHeight(), // PDRectangle.A4.getWidth())); doc.addPage(page); // Initialize table float margin = 10; float tableWidth = page.getMediaBox().getWidth() - (2 * margin); float yStartNewPage = page.getMediaBox().getHeight() - (2 * margin); float yStart = yStartNewPage; float bottomMargin = 0; // Create the data List<List> data = new ArrayList<>(); data.add(new ArrayList<>(Arrays.asList("Key", "Value"))); for (int i = 1; i <= 5; i++) { data.add(new ArrayList<>(Arrays.asList(String.valueOf(i), "value:" + i))); } BaseTable dataTable = new BaseTable( yStart, yStartNewPage, bottomMargin, tableWidth, margin, doc, page, true, true); DataTable t = new DataTable(dataTable, page); t.addListToTable(data, DataTable.HASHEADER); dataTable.draw(); File file = new File("box.pdf"); System.out.println("Sample file saved at : " + file.getAbsolutePath()); doc.save(file); } }
/** * 目次情報をPDFに挿入する。 * * @param chapterList 目次情報の配列 * @param destinationFileName 挿入先のPDFのファイル名 * @throws Exception */ public void createIndex(List<ChapterModel> chapterList, String destinationFileName) throws Exception { PDDocument document = PDDocument.load(destinationFileName); try { PDDocumentOutline outline = new PDDocumentOutline(); document.getDocumentCatalog().setDocumentOutline(outline); PDOutlineItem pagesOutline = new PDOutlineItem(); pagesOutline.setTitle("All Pages"); outline.appendChild(pagesOutline); List pages = document.getDocumentCatalog().getAllPages(); for (int i = 0; i < pages.size(); i++) { for (ChapterModel model : chapterList) { if (i == model.getPageNum()) { PDPage page = (PDPage) pages.get(i); PDPageFitWidthDestination dest = new PDPageFitWidthDestination(); dest.setPage(page); PDOutlineItem bookmark = new PDOutlineItem(); bookmark.setDestination(dest); bookmark.setTitle(model.getTitle()); pagesOutline.appendChild(bookmark); } } } pagesOutline.openNode(); outline.openNode(); document.save(destinationFileName); } catch (Exception e) { e.printStackTrace(); } finally { document.close(); } }
@Override public void outputReportToFile(String fileName) throws ReportException { try { doc.save(fileName); } catch (IOException e) { throw new ReportException("Error in report save to file: " + e.getMessage()); } }
public void printToStream( PdfPageLayout pageConfig, Resource templateResource, PdfReportStructure report, OutputStream stream, PDDocument document) throws IOException { PDDocument page = generate(pageConfig, templateResource, report, document); page.save(stream); page.close(); }
public ByteArrayOutputStream generateReport( final int lineCount, final int columnCount, List<String[]> tableContent) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Calculate center alignment for text in cell considering font height final float startTextY = tableTopY - (ROW_HEIGHT / 2) - (TEXT_LINE_HEIGHT / 4); PDDocument doc = new PDDocument(); PDPageContentStream pageStream = addPageToDoc(doc); float crtLineY = tableTopY; float crtTextY = startTextY; // draw the header float rowHeight = drawTableHeader(pageStream, columnCount, crtTextY, crtLineY); crtLineY -= rowHeight; crtTextY -= rowHeight; // draw the lines for (String[] crtLine : tableContent) { if (crtTextY <= MARGIN) { drawVerticalLines(pageStream, columnCount, crtLineY); pageStream.close(); // start new Page pageStream = addPageToDoc(doc); crtLineY = tableTopY; crtTextY = startTextY; rowHeight = drawTableHeader(pageStream, columnCount, crtTextY, crtLineY); crtLineY -= rowHeight; crtTextY -= rowHeight; } rowHeight = drawTableRow(pageStream, crtLine, columnCount, crtTextY, crtLineY); crtLineY -= rowHeight; crtTextY -= rowHeight; } drawVerticalLines(pageStream, columnCount, crtLineY); pageStream.close(); doc.save(baos); doc.close(); return baos; }
public PdfBoxWriter(PDDocument document, OutputStream output) throws IOException { this.document = document; try { this.output = output; File tempDocumentIn = new File("target/copyoffile.pdf"); tempOutput = new FileOutputStream(tempDocumentIn); document.save(tempOutput); tempOutput.close(); tempInput = new FileInputStream(tempDocumentIn); tempDocumentOut = new File("target/copyoffileout.pdf"); tempOutput = new FileOutputStream(tempDocumentOut); DSSUtils.copy(tempInput, tempOutput); tempInput.close(); tempInput = new FileInputStream(tempDocumentIn); } catch (COSVisitorException e) { throw new IOException(e); } }
/** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4); // PDPage.PAGE_SIZE_LETTER is also possible PDRectangle rect = page1.getMediaBox(); // rect can be used to get the page width and height document.addPage(page1); // Create a new font object selecting one of the PDF base fonts PDFont fontPlain = PDType1Font.HELVETICA; PDFont fontBold = PDType1Font.HELVETICA_BOLD; PDFont fontItalic = PDType1Font.HELVETICA_OBLIQUE; PDFont fontMono = PDType1Font.COURIER; // Start a new content stream which will "hold" the to be created content PDPageContentStream cos = new PDPageContentStream(document, page1); int line = 1; // Define a text content stream using the selected font, move the cursor and draw some text cos.beginText(); cos.setFont(fontPlain, 12); cos.setNonStrokingColor(Color.RED); // width is 100; height is 20 lines down everytime cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line)); cos.drawString("eeey boy"); cos.endText(); cos.beginText(); cos.setFont(fontItalic, 12); cos.setNonStrokingColor(Color.GREEN); cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line)); cos.drawString("How do you do?"); cos.endText(); cos.beginText(); cos.setFont(fontBold, 12); cos.setNonStrokingColor(Color.BLACK); cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line)); cos.drawString("Dit duurde veel langer dan nodig"); cos.endText(); cos.beginText(); cos.setFont(fontMono, 12); cos.setNonStrokingColor(Color.BLACK); cos.moveTextPositionByAmount(100, rect.getHeight() - 20 * (++line)); cos.drawString("maar ik was wat dingentjes aan t uitzoeken."); cos.endText(); // Add some gucci into this place try { BufferedImage awtImage = ImageIO.read(new File("Gucci.jpg")); PDXObjectImage ximage = new PDPixelMap(document, awtImage); float scale = 0.5f; // alter this value to set the image size cos.drawXObject(ximage, 100, 400, ximage.getWidth() * scale, ximage.getHeight() * scale); } catch (IIOException Fnfex) { System.out.println("No image for you"); } // Make sure that the content stream is closed: cos.close(); // New page PDPage page2 = new PDPage(PDPage.PAGE_SIZE_A4); document.addPage(page2); cos = new PDPageContentStream(document, page2); // draw a red box in the lower left hand corner cos.setNonStrokingColor(Color.RED); cos.fillRect(10, 10, 100, 100); // add two lines of different widths cos.setLineWidth(1); cos.addLine(200, 250, 400, 250); cos.closeAndStroke(); cos.setLineWidth(5); cos.addLine(200, 300, 400, 300); cos.closeAndStroke(); // close the content stream for page 2 cos.close(); // Save the results and ensure that the document is properly closed: document.save("GUCCI.pdf"); document.close(); }
@Test public void testAppendEncrypted() throws Exception { final String originalText = "Test"; final String textToAppend = "Append"; PDDocument document = new PDDocument(); PDPage page = new PDPage(PDPage.PAGE_SIZE_A4); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream.setFont(PDType1Font.HELVETICA, 12); contentStream.beginText(); contentStream.moveTextPositionByAmount(20, 400); contentStream.drawString(originalText); contentStream.endText(); contentStream.close(); final String ownerPass = "******"; final String userPass = "******"; AccessPermission accessPermission = new AccessPermission(); accessPermission.setCanExtractContent(false); StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(ownerPass, userPass, accessPermission); protectionPolicy.setEncryptionKeyLength(128); document.protect(protectionPolicy); ByteArrayOutputStream output = new ByteArrayOutputStream(); document.save(output); // Encryption happens after saving. PDDocument encryptedDocument = PDDocument.load(new ByteArrayInputStream(output.toByteArray())); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(PdfHeaderConstants.PDF_DOCUMENT_HEADER_NAME, encryptedDocument); headers.put( PdfHeaderConstants.DECRYPTION_MATERIAL_HEADER_NAME, new StandardDecryptionMaterial(userPass)); template.sendBodyAndHeaders("direct:start", textToAppend, headers); resultEndpoint.setExpectedMessageCount(1); resultEndpoint.expectedMessagesMatches( new Predicate() { @Override public boolean matches(Exchange exchange) { Object body = exchange.getIn().getBody(); assertThat(body, instanceOf(ByteArrayOutputStream.class)); try { PDDocument doc = PDDocument.load( new ByteArrayInputStream(((ByteArrayOutputStream) body).toByteArray())); PDFTextStripper pdfTextStripper = new PDFTextStripper(); String text = pdfTextStripper.getText(doc); assertEquals(2, doc.getNumberOfPages()); assertThat(text, containsString(originalText)); assertThat(text, containsString(textToAppend)); } catch (IOException e) { throw new RuntimeException(e); } return true; } }); resultEndpoint.assertIsSatisfied(); }
/** * @param reader * @param writer * @param options * @throws Exception */ protected final void action( Action ruleAction, NodeRef actionedUponNodeRef, ContentReader reader, Map<String, Object> options) { PDDocument pdf = null; InputStream is = null; File tempDir = null; ContentWriter writer = null; try { // Get the split frequency int splitFrequency = 0; String splitFrequencyString = options.get(PARAM_SPLIT_AT_PAGE).toString(); if (!splitFrequencyString.equals("")) { try { splitFrequency = Integer.valueOf(splitFrequencyString); } catch (NumberFormatException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } } // Get contentReader inputStream is = reader.getContentInputStream(); // stream the document in pdf = PDDocument.load(is); // split the PDF and put the pages in a list Splitter splitter = new Splitter(); // Need to adjust the input value to get the split at the right page splitter.setSplitAtPage(splitFrequency - 1); // Split the pages List<PDDocument> pdfs = splitter.split(pdf); // Start page split numbering at int page = 1; // build a temp dir, name based on the ID of the noderef we are // importing File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); // FLAG: This is ugly.....get the first PDF. PDDocument firstPDF = (PDDocument) pdfs.remove(0); int pagesInFirstPDF = firstPDF.getNumberOfPages(); String lastPage = ""; String pg = "_pg"; if (pagesInFirstPDF > 1) { pg = "_pgs"; lastPage = "-" + pagesInFirstPDF; } String fileNameSansExt = getFilenameSansExt(actionedUponNodeRef, FILE_EXTENSION); firstPDF.save( tempDir + "" + File.separatorChar + fileNameSansExt + pg + page + lastPage + FILE_EXTENSION); try { firstPDF.close(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } // FLAG: Like I said: "_UGLY_" ..... and it gets worse PDDocument secondPDF = null; Iterator<PDDocument> its = pdfs.iterator(); int pagesInSecondPDF = 0; while (its.hasNext()) { if (secondPDF != null) { // Get the split document and save it into the temp dir with // new name PDDocument splitpdf = (PDDocument) its.next(); int pagesInThisPDF = splitpdf.getNumberOfPages(); pagesInSecondPDF = pagesInSecondPDF + pagesInThisPDF; PDFMergerUtility merger = new PDFMergerUtility(); merger.appendDocument(secondPDF, splitpdf); merger.mergeDocuments(); try { splitpdf.close(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } } else { secondPDF = (PDDocument) its.next(); pagesInSecondPDF = secondPDF.getNumberOfPages(); } } if (pagesInSecondPDF > 1) { pg = "_pgs"; lastPage = "-" + (pagesInSecondPDF + pagesInFirstPDF); } else { pg = "_pg"; lastPage = ""; } // This is where we should save the appended PDF // put together the name and save the PDF secondPDF.save( tempDir + "" + File.separatorChar + fileNameSansExt + pg + splitFrequency + lastPage + FILE_EXTENSION); for (File file : tempDir.listFiles()) { try { if (file.isFile()) { // Get a writer and prep it for putting it back into the // repo NodeRef destinationNode = createDestinationNode( file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry .getContentService() .getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(reader.getEncoding()); // original // encoding writer.setMimetype(FILE_MIMETYPE); // Put it in the repo writer.putContent(file); // Clean up file.delete(); } } catch (FileExistsException e) { throw new AlfrescoRuntimeException("Failed to process file.", e); } } } catch (COSVisitorException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (pdf != null) { try { pdf.close(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } } if (is != null) { try { is.close(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } } if (tempDir != null) { tempDir.delete(); } } }
private void encrypt(String[] args) throws Exception { if (args.length < 1) { usage(); } 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(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 = new FileInputStream(certFile); X509Certificate certificate = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); recip.setX509(certificate); 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(); } } } }