List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
From source file:net.laubenberger.wichtel.helper.HelperPdf.java
License:Open Source License
/** * Modifies the meta data of given PDF and stores it in a new {@link File}. * <strong>Meta data example:"</strong> metadata.put("Title", "Example"); * metadata.put("Author", "Stefan Laubenberger"); metadata.put("Subject", * "Example PDF meta data"); metadata.put("Keywords", "Example, PDF"); * metadata.put("Creator", "http://www.laubenberger.net/"); * metadata.put("Producer", "Silvan Spross"); * //from w w w . j a v a 2s .co m * @param source * {@link File} * @param dest * {@link File} for the modified PDF * @param metadata * list with the new meta data informations * @throws DocumentException * @throws IOException * @since 0.0.1 */ @SuppressWarnings("unchecked") public static void setMetaData(final File source, final File dest, final Map<String, String> metadata) throws IOException, DocumentException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(source, dest, metadata)); if (null == source) { throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$ } if (null == dest) { throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$ } if (HelperObject.isEquals(source, dest)) { throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$ } if (null == metadata) { throw new RuntimeExceptionIsNull("metadata"); //$NON-NLS-1$ } try (FileOutputStream fos = new FileOutputStream(dest)) { final PdfReader reader = new PdfReader(source.getAbsolutePath()); final PdfStamper stamper = new PdfStamper(reader, fos); final HashMap<String, String> info = reader.getInfo(); info.putAll(metadata); stamper.setMoreInfo(info); stamper.close(); reader.close(); } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.wichtel.helper.HelperPdf.java
License:Open Source License
/** * Encrypt a PDF with a given user and password. * //from w w w.java2s . c o m * @param source * {@link File} * @param dest * {@link File} for the encrypted PDF * @param user * of the dest {@link File} * @param password * of the dest {@link File} * @throws DocumentException * @throws IOException * @since 0.0.1 */ public static void encrypt(final File source, final File dest, final byte[] user, final byte... password) throws IOException, DocumentException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(source, dest, user, password)); if (null == source) { throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$ } if (null == dest) { throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$ } if (HelperObject.isEquals(source, dest)) { throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$ } if (null == user) { throw new RuntimeExceptionIsNull("user"); //$NON-NLS-1$ } if (!HelperArray.isValid(user)) { throw new RuntimeExceptionIsEmpty("user"); //$NON-NLS-1$ } if (null == password) { throw new RuntimeExceptionIsNull("password"); //$NON-NLS-1$ } if (!HelperArray.isValid(password)) { throw new RuntimeExceptionIsEmpty("password"); //$NON-NLS-1$ } PdfReader reader = null; try (OutputStream os = new FileOutputStream(dest)) { reader = new PdfReader(source.getAbsolutePath()); PdfEncryptor.encrypt(reader, os, user, password, PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_DEGRADED_PRINTING | PdfWriter.ALLOW_FILL_IN | PdfWriter.ALLOW_MODIFY_ANNOTATIONS | PdfWriter.ALLOW_MODIFY_CONTENTS | PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS, true); } finally { if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.wichtel.helper.HelperPdf.java
License:Open Source License
/** * Adds a all restrictions to a PDF with a given password. * //from w w w. ja v a 2 s .co m * @param source * {@link File} * @param dest * {@link File} for the locked PDF * @param password * of the dest {@link File} * @throws DocumentException * @throws IOException * @since 0.0.1 */ public static void lock(final File source, final File dest, final byte... password) throws IOException, DocumentException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(source, dest, password)); if (null == source) { throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$ } if (null == dest) { throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$ } if (HelperObject.isEquals(source, dest)) { throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$ } if (null == password) { throw new RuntimeExceptionIsNull("password"); //$NON-NLS-1$ } if (!HelperArray.isValid(password)) { throw new RuntimeExceptionIsEmpty("password"); //$NON-NLS-1$ } PdfReader reader = null; try (OutputStream os = new FileOutputStream(dest)) { reader = new PdfReader(source.getAbsolutePath()); PdfEncryptor.encrypt(reader, os, null, password, 0, true); } finally { if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java
License:Open Source License
public void buildBook(List<File> inputFileList, File outputFile) { try {/*from ww w .j a v a2 s . c o m*/ float pageWidth = getConfig().getPageWidth(); float pageHeight = getConfig().getPageHeight(); // Create new Document /* float marginLeft = 36; float marginRight = 36; float marginTop = 36; float marginBottom = 36; */ if (isVerboseEnabled()) { verbose("Building output PDF file " + outputFile); } // TableOfContents toc = new TableOfContents(); ProgressMonitor progressMonitor = getConfig().getProgressMonitor(); TocRowChangeListener tocRowChangeListener = getConfig().getTocRowChangeListener(); Document outputDocument = new Document(getConfig().getPageSize()); // Document outputDocument = new Document( getPageSize(), marginLeft, marginRight, marginTop, marginBottom ); PdfWriter pdfWriter = PdfWriter.getInstance(outputDocument, new FileOutputStream(outputFile)); // TODO - review PDF page event forwarder PdfPageEventLogger pdfPageEventLogger = new PdfPageEventLogger(); pdfWriter.setPageEvent(pdfPageEventLogger); outputDocument.open(); String metaTitle = getConfig().getMetaTitle(); if (!StringUtils.isEmpty(metaTitle)) { outputDocument.addTitle(metaTitle); } String metaAuthor = getConfig().getMetaAuthor(); if (!StringUtils.isEmpty(metaAuthor)) { outputDocument.addAuthor(metaAuthor); } PdfContentByte pdfContent = pdfWriter.getDirectContent(); // Loop through and pull pages int outputPageCount = 0; int currentSourceFileIndex = 0; int maxSourceFileIndex = inputFileList.size(); // BaseFont pageLabelFont = BaseFont.createFont( PdfBookBuilderConfig.DEFAULT_FONT, BaseFont.CP1250, BaseFont.EMBEDDED ); BaseFont pageLabelFont = BaseFont.createFont(PdfBookBuilderConfig.DEFAULT_FONT_PATH, BaseFont.CP1250, BaseFont.EMBEDDED); if (isVerboseEnabled()) { verbose("Using page label font " + pageLabelFont); } if (isVerboseEnabled()) { verbose("Assembling pages using n-up " + getConfig().getNup()); } for (File sourceFile : inputFileList) { currentSourceFileIndex++; // TODO - refactor current file PDF page processing to another method // TODO - handle failover to ensure processing continues ??? if (sourceFile.isFile()) { if (isVerboseEnabled()) { verbose("Reading source PDF file " + sourceFile); } int sourcePageIndex = 0; PdfReader sourcePdfReader = new PdfReader(sourceFile.getCanonicalPath()); PdfReaderHelper sourcePdfReaderHelper = new PdfReaderHelper(sourcePdfReader); if (isVerboseEnabled()) { verbose("PDF reader is " + sourcePdfReader); verbose("PDF reader helper is " + sourcePdfReaderHelper); } String currentSourcePdfTitle = FilenameUtils.getBaseName(sourceFile.getName()); String currentSourcePdfAuthor = getSystemUserName(); if (isVerboseEnabled()) { verbose("PDF title is " + currentSourcePdfTitle); verbose("PDF author is " + currentSourcePdfAuthor); } currentSourcePdfTitle = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfTitle); currentSourcePdfAuthor = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfAuthor); if (isVerboseEnabled()) { verbose("PDF info title is " + currentSourcePdfTitle); verbose("PDF info author is " + currentSourcePdfAuthor); } boolean firstPageOfCurrentSource = true; int maxSourcePages = sourcePdfReader.getNumberOfPages(); if (isVerboseEnabled()) { verbose("There are " + maxSourcePages + " page(s) in source PDF file " + sourceFile); } // process all pages from source doc while (sourcePageIndex < maxSourcePages) { // add new page to current document outputDocument.newPage(); outputPageCount++; if (isVerboseEnabled()) { verbose("Building output PDF page " + outputPageCount + " ..."); } // add first page of current source to TOC listener if (firstPageOfCurrentSource) { int currentPageIndex = outputPageCount; if (tocRowChangeListener != null) { TocRow tocEntry = new TocRow(currentSourcePdfTitle, currentPageIndex); tocRowChangeListener.addTocRow(tocEntry); if (isVerboseEnabled()) { verbose("Added TOC entry " + tocEntry + " to listener"); } } firstPageOfCurrentSource = false; } // extract first page from source document sourcePageIndex++; if (isVerboseEnabled()) { verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages + " from source to output"); } PdfImportedPage page1 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex); // n-up is 1 if (config.getNup() == 1) { // add first page to top half of current page // TODO - review magic transformation matrix numbers and offsets // TODO - calculate scaling/transform based on page rect and template rect float p1a = 0.65f; float p1b = 0; float p1c = 0; float p1d = 0.65f; float p1e = 20; float p1f = 160; pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f); // n-up is 2 (default) } else { // add first page to top half of current page // TODO - review magic transformation matrix numbers and offsets float p1a = 0.5f; float p1b = 0; float p1c = 0; float p1d = 0.5f; float p1e = (125); float p1f = ((pageWidth / 2) + 120 + 20); pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f); // extract second page from source document ? PdfImportedPage page2 = null; if (sourcePageIndex < maxSourcePages) { sourcePageIndex++; if (isVerboseEnabled()) { verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages + " from source to output"); } page2 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex); } // add second page to bottom half of current page if (page2 != null) { // TODO - review magic transformation matrix numbers and offsets float p2a = 0.5f; float p2b = 0; float p2c = 0; float p2d = 0.5f; float p2e = 125; float p2f = 120; pdfContent.addTemplate(page2, p2a, p2b, p2c, p2d, p2e, p2f); } } /* // add first page to top half of current page // TODO - review magic transformation matrix numbers and offsets float p1a = 0.5f; float p1b = 0; float p1c = 0; float p1d = 0.5f; float p1e = (125); float p1f = ((pageWidth / 2) + 120 + 20); pdfContent.addTemplate( page1, p1a, p1b, p1c, p1d, p1e, p1f ); // add second page to bottom half of current page if (page2 != null) { // TODO - review magic transformation matrix numbers and offsets float p2a = 0.5f; float p2b = 0; float p2c = 0; float p2d = 0.5f; float p2e = 125; float p2f = 120; pdfContent.addTemplate( page2, p2a, p2b, p2c, p2d, p2e, p2f ); } */ // Add current page number to page footer String pageCountLabel = "Page " + outputPageCount; pdfContent.beginText(); pdfContent.setFontAndSize(pageLabelFont, PdfBookBuilderConfig.DEFAULT_FONT_SIZE); pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, pageCountLabel, (pageWidth / 2), 40, 0); pdfContent.endText(); } if (isVerboseEnabled()) { verbose("Finished reading " + maxSourcePages + " page(s) from source PDF file " + sourceFile); } // update progress if (isVerboseEnabled()) { if (progressMonitor != null) { int fileProgressPercentage = MathHelper.calculatePercentage(currentSourceFileIndex, maxSourceFileIndex); progressMonitor.setProgressPercentage(fileProgressPercentage); } } } } // close document outputDocument.close(); if (isVerboseEnabled()) { verbose("Output PDF file " + outputFile + " contains " + outputPageCount + " page(s)"); } // TODO - output ODT page stats summary } catch (Exception e) { String msg = "Error building PDF book: " + e.getMessage(); e.printStackTrace(System.err); System.err.println(msg); } }
From source file:net.mitnet.tools.pdf.book.pdf.util.PdfBookmarkBuilder.java
License:Open Source License
public void addBookmarks(String inputPdfFile, List<HashMap<String, Object>> bookmarks, String outputPdfFile) throws IOException, DocumentException { PdfReader reader = new PdfReader(inputPdfFile); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile)); if (bookmarks != null) { System.out.println("bookmarks.size: " + bookmarks.size()); }//from w w w .java 2s .co m System.out.println("bookmarks: " + bookmarks); stamper.setOutlines(bookmarks); stamper.addViewerPreference(PdfName.NONFULLSCREENPAGEMODE, PdfName.USEOUTLINES); stamper.close(); }
From source file:net.mitnet.tools.pdf.book.publisher.BookPublisher.java
License:Open Source License
/** * Update PDF book with meta-data./*from w ww .j a va 2 s. c o m*/ * * @see http://itext-general.2136553.n4.nabble.com/how-to-add-meta-information-to-a-document-that-is-closed-td2137179.html * @see com.lowagie.examples.general.copystamp.AddWatermarkPageNumbers */ private void updatePdfBookWithMeta(File pdfBookFile) throws IOException, DocumentException { info("updating PDF book with meta ..."); File inputPdfFile = pdfBookFile; String inputPdfFilename = inputPdfFile.getAbsolutePath(); File outputPdfFile = File.createTempFile(DEFAULT_PDF_BOOK_FILE_NAME, FileExtensionConstants.PDF_EXTENSION); debug("outputPdfFile: " + outputPdfFile); String outputPdfFilename = outputPdfFile.getAbsolutePath(); PdfReader reader = new PdfReader(inputPdfFilename); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFilename)); HashMap metaMap = new HashMap(); String metaTitle = config.getMetaTitle(); addNonEmptyMapValue(metaMap, PdfMetaKeys.TITLE, metaTitle); String metaSubject = config.getMetaSubject(); addNonEmptyMapValue(metaMap, PdfMetaKeys.SUBJECT, metaSubject); String metaKeywords = config.getMetaKeywords(); addNonEmptyMapValue(metaMap, PdfMetaKeys.KEYWORDS, metaKeywords); String metaCreator = PDF_PUBLISHER_TOOLS_IDENT + " with " + Document.getVersion(); addNonEmptyMapValue(metaMap, PdfMetaKeys.CREATOR, metaCreator); String metaAuthor = config.getMetaAuthor(); addNonEmptyMapValue(metaMap, PdfMetaKeys.AUTHOR, metaAuthor); String metaVersionId = config.getMetaVersionId(); addNonEmptyMapValue(metaMap, PdfMetaKeys.VERSION_ID, metaVersionId); debug("updating PDF book with meta map: " + metaMap); stamper.setMoreInfo(metaMap); stamper.close(); if (outputPdfFile.exists()) { FileUtils.copyFile(outputPdfFile, pdfBookFile); FileUtils.deleteQuietly(outputPdfFile); } }
From source file:net.mitnet.tools.pdf.book.publisher.BookPublisher.java
License:Open Source License
/** * Returns the number of pages in a PDF file. * //from ww w . j a va2 s.c o m * @param pdfFileName * @return * @throws IOException * * @see http://stackoverflow.com/questions/6026971/page-count-of-pdf-with-java */ private int countPdfPages(String filename) throws IOException { PdfReader reader = new PdfReader(filename); int pageCount = reader.getNumberOfPages(); reader.close(); return pageCount; }
From source file:net.mitnet.tools.pdf.book.publisher.BookPublisher.java
License:Open Source License
/** * TODO: review concat process and compare to PdfCopy. *///w w w .j a va2 s .c o m public void concatPdf(File firstPdf, File secondPdf, File concatPdf) throws IOException, DocumentException { if (isDebugEnabled()) { debug("firstPdf: " + firstPdf); debug("secondPdf: " + secondPdf); debug("concatPdf: " + concatPdf); debug("concat PDFs"); } PdfReader firstReader = new PdfReader(firstPdf.getPath()); PdfReader secondReader = new PdfReader(secondPdf.getPath()); PdfCopyFields copy = new PdfCopyFields(new FileOutputStream(concatPdf.getPath())); copy.addDocument(firstReader); copy.addDocument(secondReader); copy.close(); }
From source file:net.sf.jsignpdf.UncompressPdf.java
License:Mozilla Public License
/** * The main 'main'./*from w w w .j av a2s . c o m*/ * * @param args */ public static void main(String[] args) { if (args == null || args.length == 0) { System.out.println("Usage:\njava " + UncompressPdf.class.getName() + " file.pdf [file2.pdf [...]]"); return; } Document.compress = false; for (String tmpFile : args) { String newFileName = null; if (tmpFile.toLowerCase().endsWith(".pdf")) { newFileName = tmpFile.substring(0, tmpFile.length() - 4) + "_uncompressed.pdf"; } else { newFileName = tmpFile + "_uncompressed.pdf"; } System.out.println("Uncompressing " + tmpFile + " to " + newFileName); try { PdfReader reader = new PdfReader(tmpFile); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFileName), '\0'); int total = reader.getNumberOfPages() + 1; for (int i = 1; i < total; i++) { reader.setPageContent(i, reader.getPageContent(i)); } stamper.close(); } catch (NullPointerException npe) { npe.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:net.sf.jsignpdf.utils.PdfUtils.java
License:Mozilla Public License
/** * It tries to create PDF reader in 3 steps: * <ul>/*from w ww . j a v a2 s .c om*/ * <li>without password</li> * <li>with empty password</li> * <li>with given password</li> * </ul> * * @param aFileName * file name of PDF * @param aPassword * password * @return * @throws IOException */ public static PdfReader getPdfReader(final String aFileName, byte[] aPassword) throws IOException { PdfReader tmpReader = null; try { // try to read without password tmpReader = new PdfReader(aFileName); } catch (Exception e) { try { tmpReader = new PdfReader(aFileName, new byte[0]); } catch (Exception e2) { tmpReader = new PdfReader(aFileName, aPassword); } } return tmpReader; }