List of usage examples for org.apache.pdfbox.pdmodel PDDocument save
public void save(OutputStream output) throws IOException
From source file:noprint.NoPrint.java
/** * @param args the command line arguments * @throws IOException in case input file is can't be read or output written * @throws org.apache.pdfbox.pdmodel.encryption.BadSecurityHandlerException * @throws org.apache.pdfbox.exceptions.COSVisitorException *///w ww . j av a 2 s. c o m public static void main(String[] args) throws IOException, BadSecurityHandlerException, COSVisitorException { String infile = "input.pdf"; String outfile = "output.pdf"; String ownerPass = ""; String userPass = ""; /** * TODO: read up what the actual difference is between * userpassword and ownerpassword. */ int keylength = 40; AccessPermission ap = new AccessPermission(); PDDocument document = null; ap.setCanAssembleDocument(true); ap.setCanExtractContent(true); ap.setCanExtractForAccessibility(true); ap.setCanFillInForm(true); ap.setCanModify(true); ap.setCanModifyAnnotations(true); ap.setCanPrintDegraded(true); ap.setCanPrint(false); // YOU CAN'T PRINT // at least not when your PDFreader adheres to DRM (some don't) // also this is trivial to remove document = PDDocument.load(infile); if (!document.isEncrypted()) { StandardProtectionPolicy spp; spp = new StandardProtectionPolicy(ownerPass, userPass, ap); spp.setEncryptionKeyLength(keylength); document.protect(spp); document.save(outfile); } if (document != null) { document.close(); } }
From source file:openstitcher.core.PDFRenderer.java
License:Open Source License
public static void render(Design design, String location, ArrayList<LegendEntry> legend) throws IOException, COSVisitorException { PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page);//w ww .ja va2 s. c o m PDFont font = PDType1Font.HELVETICA; PDPageContentStream contentStream = new PDPageContentStream(document, page); float pageWidth = page.getMediaBox().getWidth(); float pageHeight = page.getMediaBox().getHeight(); float sideMargin = 70.0f; float capsMargin = 30.0f; // draw the document title contentStream.beginText(); contentStream.setFont(font, 24.0f); contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - 24.0f); contentStream.drawString(design.title); contentStream.endText(); // draw the document author contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f)); contentStream.drawString(design.author); contentStream.endText(); // draw the document license contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f + 12.0f)); contentStream.drawString(design.license); contentStream.endText(); // draw the physical size contentStream.beginText(); contentStream.setFont(font, 12.0f); contentStream.moveTextPositionByAmount(pageWidth - sideMargin - 100.0f, pageHeight - capsMargin - (24.0f + 12.0f + 12.0f)); contentStream.drawString(design.physicalSize); contentStream.endText(); // draw the pattern float gridWidth = pageWidth - (sideMargin * 2); float widthPerCell = gridWidth / (float) design.pattern.getPatternWidth(); float gridStartX = sideMargin; float gridStopX = sideMargin + (widthPerCell * design.pattern.getPatternWidth()); float gridStartY = pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f); float gridStopY = (pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f)) - (widthPerCell * design.pattern.getPatternHeight()); // draw the pattern: background for (int i = 0; i < design.pattern.getPatternWidth(); i++) { for (int j = 0; j < design.pattern.getPatternHeight(); j++) { Yarn cellYarn = design.pattern.getPatternCell(i, j); if (cellYarn != null) { contentStream.setNonStrokingColor(cellYarn.color); contentStream.fillRect(gridStartX + (widthPerCell * i), gridStartY - (widthPerCell * j) - widthPerCell, widthPerCell, widthPerCell); } } } // draw the pattern: grid outline contentStream.setStrokingColor(Color.black); for (int i = 0; i < design.pattern.getPatternWidth() + 1; i++) { // draw vertical lines float xCoord = gridStartX + (widthPerCell * i); if (i % 5 == 0) { contentStream.setLineWidth(2.0f); } else { contentStream.setLineWidth(1.0f); } contentStream.drawLine(xCoord, gridStartY, xCoord, gridStopY); } for (int i = 0; i < design.pattern.getPatternHeight() + 1; i++) { // draw horizontal lines float yCoord = gridStartY - (widthPerCell * i); if (i % 5 == 0) { contentStream.setLineWidth(2.0f); } else { contentStream.setLineWidth(1.0f); } contentStream.drawLine(gridStartX, yCoord, gridStopX, yCoord); } // draw the pattern: characters contentStream.setNonStrokingColor(Color.black); float centeringOffset = widthPerCell / 5.0f; for (int i = 0; i < design.pattern.getPatternWidth(); i++) { for (int j = 0; j < design.pattern.getPatternHeight(); j++) { Yarn cellYarn = design.pattern.getPatternCell(i, j); if (cellYarn != null) { int index = LegendEntry.findIndexByYarn(legend, cellYarn); if (index == -1) { throw new RuntimeException("Cell did not exist in legend."); } contentStream.beginText(); contentStream.setFont(font, widthPerCell); contentStream.moveTextPositionByAmount(gridStartX + (widthPerCell * i) + centeringOffset, gridStartY - (widthPerCell * j) - widthPerCell + centeringOffset); contentStream.drawString(legend.get(index).character); contentStream.endText(); } } } // draw the legend float legendWidth = pageWidth - (sideMargin * 2); float widthPerLegendCell = legendWidth / (float) legend.size(); float legendStartX = sideMargin; float legendStopX = pageWidth - sideMargin; float legendStartY = capsMargin + 12.0f; float legendStopY = capsMargin; float legendCellPadding = 1.0f; float exampleCellWidth = 10.0f; for (int i = 0; i < legend.size(); i++) { // draw box contentStream.setNonStrokingColor(legend.get(i).yarn.color); contentStream.fillRect(legendStartX + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding, exampleCellWidth, exampleCellWidth); // draw character contentStream.beginText(); contentStream.setNonStrokingColor(legend.get(i).fontColor); contentStream.setFont(font, 10.0f); contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding); contentStream.drawString(legend.get(i).character); contentStream.endText(); // draw yarn name contentStream.beginText(); contentStream.setNonStrokingColor(Color.black); contentStream.setFont(font, 10.0f); contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + exampleCellWidth + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding); contentStream.drawString(legend.get(i).yarn.name); contentStream.endText(); } contentStream.close(); document.save(location); document.close(); }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFAppendActionExecuter.java
License:Apache License
/** * @param reader/*from www . ja va 2s. c om*/ * @param writer * @param options * @throws Exception */ protected final void action(Action ruleAction, NodeRef actionedUponNodeRef, NodeRef targetNodeRef, ContentReader reader, ContentReader targetContentReader, Map<String, Object> options) { PDDocument pdf = null; PDDocument pdfTarget = null; InputStream is = null; InputStream tis = null; File tempDir = null; ContentWriter writer = null; try { is = reader.getContentInputStream(); tis = targetContentReader.getContentInputStream(); // stream the document in pdf = PDDocument.load(is); pdfTarget = PDDocument.load(tis); // Append the PDFs PDFMergerUtility merger = new PDFMergerUtility(); merger.appendDocument(pdfTarget, pdf); merger.setDestinationFileName(options.get(PARAM_DESTINATION_NAME).toString()); merger.mergeDocuments(); // 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(); String fileName = options.get(PARAM_DESTINATION_NAME).toString(); pdfTarget.save(tempDir + "" + File.separatorChar + fileName + 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 (pdfTarget != null) { try { pdfTarget.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(); } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFInsertAtPageActionExecuter.java
License:Apache License
/** * @param reader// w ww . j a v a2s . com * @param writer * @param options * @throws Exception */ protected final void action(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader reader, ContentReader insertReader, Map<String, Object> options) { PDDocument pdf = null; PDDocument insertContentPDF = null; InputStream is = null; InputStream cis = null; File tempDir = null; ContentWriter writer = null; try { int insertAt = Integer.valueOf((String) options.get(PARAM_INSERT_AT_PAGE)).intValue(); // Get contentReader inputStream is = reader.getContentInputStream(); // Get insertContentReader inputStream cis = insertReader.getContentInputStream(); // stream the target document in pdf = PDDocument.load(is); // stream the insert content document in insertContentPDF = PDDocument.load(cis); // 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(insertAt - 1); // Split the pages List<PDDocument> pdfs = splitter.split(pdf); // Build the output PDF PDFMergerUtility merger = new PDFMergerUtility(); merger.appendDocument((PDDocument) pdfs.get(0), insertContentPDF); merger.appendDocument((PDDocument) pdfs.get(0), (PDDocument) pdfs.get(1)); merger.setDestinationFileName(options.get(PARAM_DESTINATION_NAME).toString()); merger.mergeDocuments(); // 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(); String fileName = options.get(PARAM_DESTINATION_NAME).toString(); PDDocument completePDF = (PDDocument) pdfs.get(0); completePDF.save(tempDir + "" + File.separatorChar + fileName + FILE_EXTENSION); try { completePDF.close(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } 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); } } } // TODO add better handling 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(); } } }
From source file:org.alfresco.repo.content.transform.OOoContentTransformerHelper.java
License:Open Source License
/** * This method produces an empty PDF file at the specified File location. * Apache's PDFBox is used to create the PDF file. *///from w w w.j ava 2 s. c om private void produceEmptyPdfFile(File tempToFile) { // If improvement PDFBOX-914 is incorporated, we can do this with a straight call to // org.apache.pdfbox.TextToPdf.createPDFFromText(new StringReader("")); // https://issues.apache.org/jira/browse/PDFBOX-914 PDDocument pdfDoc = null; PDPageContentStream contentStream = null; try { pdfDoc = new PDDocument(); PDPage pdfPage = new PDPage(); // Even though, we want an empty PDF, some libs (e.g. PDFRenderer) object to PDFs // that have literally nothing in them. So we'll put a content stream in it. contentStream = new PDPageContentStream(pdfDoc, pdfPage); pdfDoc.addPage(pdfPage); // Now write the in-memory PDF document into the temporary file. pdfDoc.save(tempToFile.getAbsolutePath()); } catch (COSVisitorException cvx) { throw new ContentIOException("Error creating empty PDF file", cvx); } catch (IOException iox) { throw new ContentIOException("Error creating empty PDF file", iox); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException ignored) { // Intentionally empty } } if (pdfDoc != null) { try { pdfDoc.close(); } catch (IOException ignored) { // Intentionally empty. } } } }
From source file:org.alfresco.repo.content.transform.TextToPdfContentTransformer.java
License:Open Source License
@Override protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options) throws Exception { PDDocument pdf = null; InputStream is = null;/* w w w. ja v a2 s . c om*/ InputStreamReader ir = null; OutputStream os = null; try { is = reader.getContentInputStream(); ir = buildReader(is, reader.getEncoding(), reader.getContentUrl()); TransformationOptionLimits limits = getLimits(reader, writer, options); TransformationOptionPair pageLimits = limits.getPagesPair(); pdf = transformer.createPDFFromText(ir, pageLimits, reader.getContentUrl()); // dump it all to the writer os = writer.getContentOutputStream(); pdf.save(os); } finally { if (pdf != null) { try { pdf.close(); } catch (Throwable e) { e.printStackTrace(); } } if (ir != null) { try { ir.close(); } catch (Throwable e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (Throwable e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Throwable e) { e.printStackTrace(); } } } }
From source file:org.apache.camel.component.pdf.PdfAppendTest.java
License:Apache License
@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);//from w w w . j a va2 s . com 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 = "ownerPass"; final String userPass = "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(); }
From source file:org.apache.camel.component.pdf.PdfProducer.java
License:Apache License
private Object doAppend(Exchange exchange) throws IOException, BadSecurityHandlerException, CryptographyException, InvalidPasswordException, COSVisitorException { LOG.debug("Got {} operation, going to append text to provided pdf.", pdfConfiguration.getOperation()); String body = exchange.getIn().getBody(String.class); PDDocument document = exchange.getIn().getHeader(PDF_DOCUMENT_HEADER_NAME, PDDocument.class); if (document == null) { throw new IllegalArgumentException( String.format("%s header is expected for append operation", PDF_DOCUMENT_HEADER_NAME)); }// w w w .ja v a 2 s . c o m if (document.isEncrypted()) { DecryptionMaterial decryptionMaterial = exchange.getIn().getHeader(DECRYPTION_MATERIAL_HEADER_NAME, DecryptionMaterial.class); if (decryptionMaterial == null) { throw new IllegalArgumentException( String.format("%s header is expected for %s operation " + "on encrypted document", DECRYPTION_MATERIAL_HEADER_NAME, pdfConfiguration.getOperation())); } document.openProtection(decryptionMaterial); document.setAllSecurityToBeRemoved(true); } ProtectionPolicy protectionPolicy = exchange.getIn().getHeader(PROTECTION_POLICY_HEADER_NAME, ProtectionPolicy.class); appendToPdfDocument(body, document, protectionPolicy); OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.save(byteArrayOutputStream); return byteArrayOutputStream; }
From source file:org.apache.camel.component.pdf.PdfProducer.java
License:Apache License
private OutputStream doCreate(Exchange exchange) throws IOException, BadSecurityHandlerException, COSVisitorException { LOG.debug("Got {} operation, going to create and write provided string to pdf document.", pdfConfiguration.getOperation()); String body = exchange.getIn().getBody(String.class); PDDocument document = new PDDocument(); StandardProtectionPolicy protectionPolicy = exchange.getIn().getHeader(PROTECTION_POLICY_HEADER_NAME, StandardProtectionPolicy.class); appendToPdfDocument(body, document, protectionPolicy); OutputStream byteArrayOutputStream = new ByteArrayOutputStream(); document.save(byteArrayOutputStream); return byteArrayOutputStream; }
From source file:org.apache.camel.component.pdf.PdfTextExtractionTest.java
License:Apache License
@Test public void testExtractTextFromEncrypted() throws Exception { final String ownerPass = "ownerPass"; final String userPass = "userPass"; AccessPermission accessPermission = new AccessPermission(); accessPermission.setCanExtractContent(false); StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(ownerPass, userPass, accessPermission);// w w w .j ava 2 s . c o m protectionPolicy.setEncryptionKeyLength(128); PDDocument document = new PDDocument(); final String expectedText = "Test string"; 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(expectedText); contentStream.endText(); contentStream.close(); document.protect(protectionPolicy); ByteArrayOutputStream output = new ByteArrayOutputStream(); document.save(output); // Encryption happens after saving. PDDocument encryptedDocument = PDDocument.load(new ByteArrayInputStream(output.toByteArray())); template.sendBodyAndHeader("direct:start", encryptedDocument, PdfHeaderConstants.DECRYPTION_MATERIAL_HEADER_NAME, new StandardDecryptionMaterial(userPass)); resultEndpoint.setExpectedMessageCount(1); resultEndpoint.expectedMessagesMatches(new Predicate() { @Override public boolean matches(Exchange exchange) { Object body = exchange.getIn().getBody(); assertThat(body, instanceOf(String.class)); assertThat((String) body, containsString(expectedText)); return true; } }); resultEndpoint.assertIsSatisfied(); document.isEncrypted(); }