List of usage examples for com.itextpdf.text.pdf PdfReader getNumberOfPages
public int getNumberOfPages()
From source file:net.japt.transpdf.TransPDF.java
License:Apache License
/** * Translate English PDF to Spanish Text * /* w w w . j ava 2 s . c o m*/ * @param pdfFile String Path of the PDF Document * @param textFile String Path of the Translated Text Document */ public static void translate(String pdfFile, String textFile) { try { PdfReader pdfReader = new PdfReader(pdfFile); FileWriter transTxtFile = new FileWriter(textFile, true); int numPages = pdfReader.getNumberOfPages(); Translator translate = Translator.getInstance(); for (int i = 1; i <= numPages; i++) { // Pages String pageText = com.itextpdf.text.pdf.parser.PdfTextExtractor.getTextFromPage(pdfReader, i); // Paragraph String[] lines = pageText.split("\n"); if (lines.length == 0) { lines = new String[1]; lines[0] = pageText; } for (int nl = 0; nl < lines.length; nl++) { String transLine = ""; // Points String[] points = lines[nl].split("\\."); if (points.length == 0) { points = new String[1]; points[0] = lines[nl]; } for (int np = 0; np < points.length; np++) { // Commas String[] commas = points[np].split(","); if (commas.length == 0) { commas = new String[1]; commas[0] = points[np]; } for (int nc = 0; nc < commas.length; nc++) { if (commas[nc].length() > 0) { String translatedText = translate.translate(commas[nc], Language.ENGLISH, Language.SPANISH); transLine = transLine + " " + translatedText; } } } transTxtFile.write(transLine + "\n"); } } transTxtFile.flush(); transTxtFile.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.pflaeging.PortableSigner.PDFSigner.java
License:Open Source License
/** Creates a new instance of DoSignPDF */ public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password, Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment, String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin, float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException { try {/*from w ww. j a v a2s . c om*/ //System.out.println("-> DoSignPDF <-"); //System.out.println("Eingabedatei: " + pdfInputFileName); //System.out.println("Ausgabedatei: " + pdfOutputFileName); //System.out.println("Signaturdatei: " + pkcs12FileName); //System.out.println("Signaturblock?: " + signText); //System.out.println("Sprache der Blocks: " + signLanguage); //System.out.println("Signaturlogo: " + sigLogo); System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin); Rectangle signatureBlock; java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2); pkcs12 = new GetPKCS12(pkcs12FileName, password); PdfReader reader = null; try { // System.out.println("Password:" + ownerPassword.toString()); if (ownerPassword == null) reader = new PdfReader(pdfInputFileName); else reader = new PdfReader(pdfInputFileName, ownerPassword); } catch (IOException e) { /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle( "net/pflaeging/PortableSigner/i18n").getString( "CouldNotBeOpened"), true, e.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("CouldNotBeOpened"), true, e.getLocalizedMessage()); } FileOutputStream fout = null; try { fout = new FileOutputStream(pdfOutputFileName); } catch (FileNotFoundException e) { /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"), true, e.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("CouldNotBeWritten"), true, e.getLocalizedMessage()); } PdfStamper stp = null; try { Date datum = new Date(System.currentTimeMillis()); int pages = reader.getNumberOfPages(); Rectangle size = reader.getPageSize(pages); stp = PdfStamper.createSignature(reader, fout, '\0', null, true); HashMap<String, String> pdfInfo = reader.getInfo(); // thanks to Markus Feisst String pdfInfoProducer = ""; if (pdfInfo.get("Producer") != null) { pdfInfoProducer = pdfInfo.get("Producer").toString(); pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")"; } else { pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")"; } pdfInfo.put("Producer", pdfInfoProducer); //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString()); stp.setMoreInfo(pdfInfo); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XmpWriter xmp = new XmpWriter(baos, pdfInfo); xmp.close(); stp.setXmpMetadata(baos.toByteArray()); if (signText) { String greet, signator, datestr, ca, serial, special, note, urn, urnvalue; int specialcount = 0; int sigpage; int rightMarginPT, leftMarginPT; float verticalPositionPT; ResourceBundle block = ResourceBundle .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage); greet = block.getString("greeting"); signator = block.getString("signator"); datestr = block.getString("date"); ca = block.getString("issuer"); serial = block.getString("serial"); special = block.getString("special"); note = block.getString("note"); urn = block.getString("urn"); urnvalue = block.getString("urnvalue"); //sigcomment = block.getString(signLanguage + "-comment"); // upper y float topy = size.getTop(); System.err.println("Top: " + topy * ptToCm); // right x float rightx = size.getRight(); System.err.println("Right: " + rightx * ptToCm); if (!noExtraPage) { sigpage = pages + 1; stp.insertPage(sigpage, size); // 30pt left, 30pt right, 20pt from top rightMarginPT = 30; leftMarginPT = 30; verticalPositionPT = topy - 20; } else { if (signLastPage) { sigpage = pages; } else { sigpage = 1; } System.err.println("Page: " + sigpage); rightMarginPT = Math.round(rightMargin / ptToCm); leftMarginPT = Math.round(leftMargin / ptToCm); verticalPositionPT = topy - Math.round(verticalPos / ptToCm); } if (!GetPKCS12.atEgovOID.equals("")) { specialcount = 1; } PdfContentByte content = stp.getOverContent(sigpage); float[] cellsize = new float[2]; cellsize[0] = 100f; // rightx = width of page // 60 = 2x30 margins // cellsize[0] = description row // cellsize[1] = 0 // 70 = logo width cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70; // Pagetable = Greeting, signatureblock, comment // sigpagetable = outer table // consist: greetingcell, signatureblock , commentcell PdfPTable signatureBlockCompleteTable = new PdfPTable(2); PdfPTable signatureTextTable = new PdfPTable(2); PdfPCell signatureBlockHeadingCell = new PdfPCell( new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12)))); signatureBlockHeadingCell.setPaddingBottom(5); signatureBlockHeadingCell.setColspan(2); signatureBlockHeadingCell.setBorderWidth(0f); signatureBlockCompleteTable.addCell(signatureBlockHeadingCell); // inner table start // Line 1 signatureTextTable.addCell( new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell( new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10)))); // Line 2 signatureTextTable.addCell( new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell( new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10)))); // Line 3 signatureTextTable.addCell( new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell( new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10)))); // Line 4 signatureTextTable.addCell( new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell(new Paragraph( new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10)))); // Line 5 if (specialcount == 1) { signatureTextTable.addCell(new Paragraph( new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable.addCell(new Paragraph( new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10)))); } signatureTextTable.addCell( new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); signatureTextTable .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10)))); signatureTextTable.setTotalWidth(cellsize); System.err.println( "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm); // inner table end signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER); Image logo; // System.out.println("Logo:" + sigLogo + ":"); if (sigLogo == null || "".equals(sigLogo)) { logo = Image.getInstance( getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png")); } else { logo = Image.getInstance(sigLogo); } PdfPCell logocell = new PdfPCell(); logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); logocell.setImage(logo); signatureBlockCompleteTable.addCell(logocell); PdfPCell incell = new PdfPCell(signatureTextTable); incell.setBorderWidth(0f); signatureBlockCompleteTable.addCell(incell); PdfPCell commentcell = new PdfPCell( new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10)))); PdfPCell notecell = new PdfPCell( new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD)))); //commentcell.setPaddingTop(10); //commentcell.setColspan(2); // commentcell.setBorderWidth(0f); if (!sigComment.equals("")) { signatureBlockCompleteTable.addCell(notecell); signatureBlockCompleteTable.addCell(commentcell); } float[] cells = { 70, cellsize[0] + cellsize[1] }; signatureBlockCompleteTable.setTotalWidth(cells); System.err.println( "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm); signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT, verticalPositionPT, content); System.err.println( "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm); signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20, topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20); // ////// // AcroFields af = reader.getAcroFields(); // ArrayList names = af.getSignatureNames(); // for (int k = 0; k < names.size(); ++k) { // String name = (String) names.get(k); // System.out.println("Signature name: " + name); // System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name)); // System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions()); // PdfPKCS7 pk = af.verifySignature(name); // X509Certificate tempsigner = pk.getSigningCertificate(); // Calendar cal = pk.getSignDate(); // Certificate pkc[] = pk.getCertificates(); // java.util.ResourceBundle tempoid = // java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID"); // String tmpEgovOID = ""; // // for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) { // String element = o.nextElement(); // // System.out.println(element + ":" + oid.getString(element)); // if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) { // if (!tmpEgovOID.equals("")) { // tmpEgovOID += ", "; // } // tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")"; // } // } // //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate())); // System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString()); // System.out.println("\tDatum: " + cal.getTime().toString()); // System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString()); // System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber()); // if (!tmpEgovOID.equals("")) { // System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID); // } // System.out.println("\n"); // System.out.println("\tDocument modified: " + !pk.verify()); //// Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal); //// if (fails == null) { //// System.out.println("\tCertificates verified against the KeyStore"); //// } else { //// System.out.println("\tCertificate failed: " + fails[1]); //// } // } // // ////// } else { signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition } PdfSignatureAppearance sap = stp.getSignatureAppearance(); // sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, // PdfSignatureAppearance.WINCER_SIGNED ); sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null); sap.setReason(signReason); sap.setLocation(signLocation); // if (signText) { // sap.setVisibleSignature(signatureBlock, // pages + 1, "PortableSigner"); // } if (finalize) { sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); } else { sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED); } stp.close(); /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"), false, ""); */ } catch (Exception e) { /* MODIFY BY: Denis Torresan Main.setResult( java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage()); } } catch (KeyStoreException kse) { /* MODIFY BY: Denis Torresan Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage()); */ throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n") .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage()); } }
From source file:net.sf.regain.crawler.preparator.PdfItextPreparator.java
License:Open Source License
/** * Prpariert ein Dokument fr die Indizierung. * * @param rawDocument Das zu prpariernde Dokument. * @throws net.sf.regain.RegainException Wenn die Prparation fehl schlug. *//*from www. ja va 2 s . c o m*/ @SuppressWarnings("unchecked") public void prepare(RawDocument rawDocument) throws RegainException { String url = rawDocument.getUrl(); InputStream stream = null; PdfReader reader = null; try { // Create a InputStream that reads the content. stream = rawDocument.getContentAsStream(); // Parse the content reader = new PdfReader(stream); if (reader.isEncrypted()) { reader = new PdfReader(stream, OWNER_PASSWORD); } PdfReaderContentParser parser = new PdfReaderContentParser(reader); TextExtractionStrategy strategy; StringBuilder stringBuilder = new StringBuilder(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { strategy = parser.processContent(i, new SimpleTextExtractionStrategy()); stringBuilder.append(strategy.getResultantText()); } setCleanedContent(stringBuilder.toString()); // Get metadata Map<String, String> info = reader.getInfo(); StringBuilder metaData = new StringBuilder(); metaData.append("p."); metaData.append(Integer.toString(reader.getNumberOfPages())); metaData.append(" "); // Check if fields are null String author = info.get("Author"); String creator = info.get("Creator"); String subject = info.get("Subject"); String keywords = info.get("Keywords"); String title = info.get("Title"); if (author != null) { metaData.append(author); metaData.append(" "); } if (creator != null) { metaData.append(creator); metaData.append(" "); } if (subject != null) { metaData.append(subject); metaData.append(" "); } if (keywords != null) { metaData.append(keywords); metaData.append(" "); } if (title != null) { setTitle(title); } setCleanedMetaData(metaData.toString()); if (log.isDebugEnabled()) { log.debug("Extracted meta data ::" + getCleanedMetaData() + ":: from " + rawDocument.getUrl()); } } catch (IOException exc) { throw new RegainException("Error reading document: " + url, exc); } catch (Exception exc) { // They didn't supply a password and the default of "" was wrong. throw new RegainException("Unknown error parsing document: " + url, exc); } finally { if (stream != null) { try { stream.close(); } catch (Exception exc) { } } if (reader != null) { try { reader.close(); } catch (Exception exc) { } } } }
From source file:no.dusken.aranea.admin.control.issue.IssueIndexer.java
License:Apache License
private void addPagesToIssue(PdfReader pdfReader, Issue issue) throws IOException { for (int pageNumber = 1; pageNumber <= pdfReader.getNumberOfPages(); pageNumber++) { addPageToIssue(pageNumber, pdfReader, issue); }/*from w w w . j a v a 2 s .co m*/ }
From source file:nz.ac.waikato.cms.doc.HyperLinkGrades.java
License:Open Source License
/** * Adds the index with locations to the existing PDF. * * @param locations the locations to index * @param input the input PDF/*ww w .j av a2 s. co m*/ * @param output the output PDF * @return true if successfully generated */ public static boolean addIndex(List<Location> locations, File input, File output) { try { // copy pages, add target PdfReader reader = new PdfReader(input.getAbsolutePath()); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(output.getAbsolutePath())); document.open(); PdfContentByte canvas = writer.getDirectContent(); PdfImportedPage page; float height = 0; for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); page = writer.getImportedPage(reader, i); canvas.addTemplate(page, 1f, 0, 0, 1, 0, 0); Chunk loc = new Chunk(" "); loc.setLocalDestination("loc" + i); height = page.getHeight(); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(loc), 50, height - 50, 0); } // add index for (int i = 0; i < locations.size(); i++) { Location loc = locations.get(i); if (i % MAX_ITEMS_PER_PAGE == 0) document.newPage(); String text = loc.getID() + " " + (loc.getName() == null ? "???" : loc.getName()); Chunk chunk = new Chunk("Page " + (loc.getPage() + 1) + ": " + text); chunk.setAction(PdfAction.gotoLocalPage("loc" + (loc.getPage() + 1), false)); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(chunk), 50, height - 100 - (i % MAX_ITEMS_PER_PAGE) * 20, 0); } document.close(); return true; } catch (Exception e) { System.err.println("Failed to overlay locations!"); e.printStackTrace(); return false; } }
From source file:nz.ac.waikato.cms.doc.OverlayFilename.java
License:Open Source License
/** * Performs the overlay.// w w w . ja v a2s . com * * @param input the input file/dir * @param output the output file/dir * @param vpos the vertical position * @param hpos the horizontal position * @param stripPath whether to strip the path * @param stripExt whether to strip the extension * @param pages the array of pages (1-based) to add the overlay to, null for all * @param evenPages whether to enforce even pages in the document * @return true if successfully overlay */ public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt, int[] pages, boolean evenPages) { PdfReader reader; PdfStamper stamper; FileOutputStream fos; PdfContentByte canvas; int i; String text; int numPages; File tmpFile; Document document; PdfWriter writer; PdfImportedPage page; PdfContentByte cb; reader = null; stamper = null; fos = null; numPages = -1; try { reader = new PdfReader(input.getAbsolutePath()); fos = new FileOutputStream(output.getAbsolutePath()); stamper = new PdfStamper(reader, fos); numPages = reader.getNumberOfPages(); if (pages == null) { pages = new int[reader.getNumberOfPages()]; for (i = 0; i < pages.length; i++) pages[i] = i + 1; } if (stripPath) text = input.getName(); else text = input.getAbsolutePath(); if (stripExt) text = text.replaceFirst("\\.[pP][dD][fF]$", ""); for (i = 0; i < pages.length; i++) { canvas = stamper.getOverContent(pages[i]); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f); } } catch (Exception e) { System.err.println("Failed to process " + input + ":"); e.printStackTrace(); return false; } finally { try { if (stamper != null) stamper.close(); } catch (Exception e) { // ignored } try { if (reader != null) reader.close(); } catch (Exception e) { // ignored } try { if (fos != null) { fos.flush(); fos.close(); } } catch (Exception e) { // ignored } } // enforce even pages? if (evenPages && (numPages > 0) && (numPages % 2 == 1)) { reader = null; fos = null; writer = null; tmpFile = new File(output.getAbsolutePath() + "tmp"); try { if (!output.renameTo(tmpFile)) { System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!"); return false; } reader = new PdfReader(tmpFile.getAbsolutePath()); document = new Document(reader.getPageSize(1)); fos = new FileOutputStream(output.getAbsoluteFile()); writer = PdfWriter.getInstance(document, fos); document.open(); document.addCreationDate(); document.addAuthor(System.getProperty("user.name")); cb = writer.getDirectContent(); for (i = 0; i < reader.getNumberOfPages(); i++) { page = writer.getImportedPage(reader, i + 1); document.newPage(); cb.addTemplate(page, 0, 0); } document.newPage(); document.add(new Paragraph(" ")); // fake content document.close(); } catch (Exception e) { System.err.println("Failed to process " + tmpFile + ":"); e.printStackTrace(); return false; } finally { try { if (fos != null) { fos.flush(); fos.close(); } } catch (Exception e) { // ignored } try { if (reader != null) reader.close(); } catch (Exception e) { // ignored } try { if (writer != null) writer.close(); } catch (Exception e) { // ignored } if (tmpFile.exists()) { try { tmpFile.delete(); } catch (Exception e) { // ignored } } } } return true; }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
License:Apache License
/** * Applies an image watermark/* www . jav a 2 s . com*/ * * @param reader * @param writer * @param options * @throws Exception */ private void imageAction(Action ruleAction, NodeRef actionedUponNodeRef, NodeRef watermarkNodeRef, ContentReader actionedUponContentReader, ContentReader watermarkContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; try { // get a temp file to stash the watermarked PDF in before moving to // repo File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); // get the PDF input stream and create a reader for iText PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); PdfContentByte pcb; // get a com.itextpdf.text.Image object via java.imageio.ImageIO Image img = Image.getInstance(ImageIO.read(watermarkContentReader.getContentInputStream()), null); // get the PDF pages and position String pages = (String) options.get(PARAM_PAGE); String position = (String) options.get(PARAM_POSITION); String depth = (String) options.get(PARAM_WATERMARK_DEPTH); // image requires absolute positioning or an exception will be // thrown // set image position according to parameter. Use // PdfReader.getPageSizeWithRotation // to get the canvas size for alignment. img.setAbsolutePosition(100f, 100f); // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // set stamp position if (position.equals(POSITION_BOTTOMLEFT)) { img.setAbsolutePosition(0, 0); } else if (position.equals(POSITION_BOTTOMRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), 0); } else if (position.equals(POSITION_TOPLEFT)) { img.setAbsolutePosition(0, r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_TOPRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_CENTER)) { img.setAbsolutePosition(getCenterX(r, img), getCenterY(r, img)); } // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, usse getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { pcb.addImage(img); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
License:Apache License
/** * Applies a text watermark (current date, user name, etc, depending on * options)/*from w w w .jav a2 s . co m*/ * * @param reader * @param writer * @param options */ private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; String watermarkText; StringTokenizer st; Vector<String> tokens = new Vector<String>(); try { // get a temp file to stash the watermarked PDF in before moving to // repo File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); // get the PDF input stream and create a reader for iText PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); PdfContentByte pcb; // get the PDF pages and position String pages = (String) options.get(PARAM_PAGE); String position = (String) options.get(PARAM_POSITION); String depth = (String) options.get(PARAM_WATERMARK_DEPTH); // create the base font for the text stamp BaseFont bf = BaseFont.createFont((String) options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250, BaseFont.EMBEDDED); // get watermark text and process template with model String templateText = (String) options.get(PARAM_WATERMARK_TEXT); Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef); StringWriter watermarkWriter = new StringWriter(); freemarkerProcessor.processString(templateText, model, watermarkWriter); watermarkText = watermarkWriter.getBuffer().toString(); // tokenize watermark text to support multiple lines and copy tokens // to vector for re-use st = new StringTokenizer(watermarkText, "\r\n", false); while (st.hasMoreTokens()) { tokens.add(st.nextToken()); } // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, use getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // set the font and size float size = Float.parseFloat((String) options.get(PARAM_WATERMARK_SIZE)); pcb.setFontAndSize(bf, size); // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { writeAlignedText(pcb, r, tokens, size, position); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.arc42.pdfutil.PdfChecker.java
License:Open Source License
static int countPagesInPdf(String candidate) { // LOGGER.log(Level.INFO, System.getProperty("user.dir")); PdfReader reader = null; try {/*from ww w . j a va2 s.co m*/ reader = new PdfReader(candidate); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Exception: file not found - therefore I cannot count pages", e); } return reader.getNumberOfPages(); }
From source file:org.arc42.pdfutil.PdfConcatenizer.java
License:Open Source License
/** * concats all files given in sourceFile */// w w w . java 2 s . c o m public void concatFiles() { Document document = new Document(); try { PdfCopy copy = new PdfCopy(document, new FileOutputStream(targetFileName)); document.open(); PdfReader reader; int nrOfPagesInCurrentFile; for (int i = 0; i < sourceFiles.size(); i++) { reader = new PdfReader(sourceFiles.get(i)); nrOfPagesInCurrentFile = reader.getNumberOfPages(); for (int page = 0; page < nrOfPagesInCurrentFile;) { copy.addPage(copy.getImportedPage(reader, ++page)); } if (evenify && (nrOfPagesInCurrentFile % 2 == 1)) { addBlankPage(copy); } } document.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Exception: wrong file you gave me, Yoda muttered...", e); } catch (BadPdfFormatException e) { LOGGER.log(Level.SEVERE, "Exception: Encountered bad pdf format", e); } catch (DocumentException e) { LOGGER.log(Level.SEVERE, "Exception: Something bad happened to the output document.", e); } }