List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
From source file:lucee.runtime.tag.Document.java
License:Open Source License
private void render(OutputStream os, boolean doBookmarks, boolean doHtmlBookmarks) throws IOException, PageException, DocumentException { byte[] pdf = null; // merge multiple docs to 1 if (documents.size() > 1) { PDFDocument[] pdfDocs = new PDFDocument[documents.size()]; PdfReader[] pdfReaders = new PdfReader[pdfDocs.length]; Iterator<PDFDocument> it = documents.iterator(); int index = 0; // generate pdf with pd4ml while (it.hasNext()) { pdfDocs[index] = it.next();//from w ww . ja v a2 s. com pdfReaders[index] = new PdfReader( pdfDocs[index].render(getDimension(), unitFactor, pageContext, doHtmlBookmarks)); index++; } // collect together ByteArrayOutputStream baos = new ByteArrayOutputStream(); com.lowagie.text.Document document = new com.lowagie.text.Document( pdfReaders[0].getPageSizeWithRotation(1)); PdfCopy copy = new PdfCopy(document, baos); document.open(); String name; ArrayList bookmarks = doBookmarks ? new ArrayList() : null; try { int size, totalPage = 0; Map parent; for (int doc = 0; doc < pdfReaders.length; doc++) { size = pdfReaders[doc].getNumberOfPages(); PdfImportedPage ip; // bookmarks if (doBookmarks) { name = pdfDocs[doc].getName(); if (!StringUtil.isEmpty(name)) { bookmarks.add(parent = PDFUtil.generateGoToBookMark(name, totalPage + 1)); } else parent = null; if (doHtmlBookmarks) { java.util.List pageBM = SimpleBookmark.getBookmark(pdfReaders[doc]); if (pageBM != null) { if (totalPage > 0) SimpleBookmark.shiftPageNumbers(pageBM, totalPage, null); if (parent != null) PDFUtil.setChildBookmarks(parent, pageBM); else bookmarks.addAll(pageBM); } } } totalPage++; for (int page = 1; page <= size; page++) { if (page > 1) totalPage++; ip = copy.getImportedPage(pdfReaders[doc], page); //ip.getPdfDocument().setHeader(arg0); //ip.getPdfDocument().setFooter(arg0); copy.addPage(ip); } } if (doBookmarks && !bookmarks.isEmpty()) copy.setOutlines(bookmarks); } finally { document.close(); } pdf = baos.toByteArray(); } else if (documents.size() == 1) { pdf = (documents.get(0)).render(getDimension(), unitFactor, pageContext, doHtmlBookmarks); } else { pdf = getDocument().render(getDimension(), unitFactor, pageContext, doHtmlBookmarks); } // permission/encryption if (PDFDocument.ENC_NONE != encryption) { PdfReader reader = new PdfReader(pdf); com.lowagie.text.Document document = new com.lowagie.text.Document(reader.getPageSize(1)); document.addCreator("Lucee " + Info.getVersionAsString() + " " + Info.getStateAsString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfCopy copy = new PdfCopy(document, baos); //PdfWriter writer = PdfWriter.getInstance(document, pdfOut); copy.setEncryption(PDFDocument.ENC_128BIT == encryption, userpassword, ownerpassword, permissions); document.open(); int size = reader.getNumberOfPages(); for (int page = 1; page <= size; page++) { copy.addPage(copy.getImportedPage(reader, page)); } document.close(); pdf = baos.toByteArray(); } // write out if (os != null) IOUtil.copy(new ByteArrayInputStream(pdf), os, true, false); if (!StringUtil.isEmpty(name)) { pageContext.setVariable(name, pdf); } }
From source file:managedbean.aas.reportController.java
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) { Document document = new Document(); try {/*from ww w . ja va2 s. c o m*/ List<InputStream> pdfs = streamOfPDFFiles; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); // Code for pagination. if (paginate) { cb.beginText(); cb.setFontAndSize(bf, 9); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber + " of " + totalPages, 520, 5, 0); cb.endText(); } } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } }
From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java
License:Open Source License
private byte[] encryptPDF(byte[] unencryptedPDF, String userPassword, String ownerPassword) throws IOException, DocumentException { PdfReader pdfReader = new PdfReader(unencryptedPDF); ByteArrayOutputStream encryptedPDF = new ByteArrayOutputStream(unencryptedPDF.length + ENCRYPTION_OVERHEAD); PdfEncryptor.encrypt(pdfReader, encryptedPDF, pdfEncryptionType, userPassword, ownerPassword, getOpenPermissionsIntValue()); return encryptedPDF.toByteArray(); }
From source file:mpv5.utils.export.Export.java
License:Open Source License
private static File mergeFiles(List<File> p) { Document document = new Document(); try {// w w w .j av a 2s. co m List<InputStream> pdfs = new ArrayList<InputStream>(); for (int i = 0; i < p.size(); i++) { File inputStream = p.get(i); pdfs.add(new FileInputStream(inputStream)); } List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } File f = FileDirectoryHandler.getTempFile("pdf"); FileOutputStream outputstream = new FileOutputStream(f); PdfWriter writer = PdfWriter.getInstance(document, outputstream); document.open(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); } pageOfCurrentReaderPDF = 0; } outputstream.flush(); document.close(); outputstream.close(); return f; } catch (Exception e) { Log.Debug(e); } finally { if (document.isOpen()) { document.close(); } } return null; }
From source file:mpv5.utils.export.PDFFile.java
License:Open Source License
@Override public void run() { Log.Debug(this, "All fields:"); for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) { String k = it.next();/*from w ww . ja va 2 s . c o m*/ Log.Debug(this, "Key: " + k + " [" + getData().get(k) + "]"); } try { Log.Debug(this, "Running export for template file: " + getPath() + " to file: " + getTarget()); try { template = new PdfReader(getPath()); } catch (Exception iOException) { Log.Debug(iOException); } Log.Debug(this, "Checking PDF File: " + getPath()); acroFields = template.getAcroFields(); Log.Debug(this, "Creating PDF File: " + getTarget().getPath()); PdfStamper pdfStamper = new PdfStamper(template, new FileOutputStream(getTarget().getPath())); pdfStamper.setFormFlattening(true); acroFields = pdfStamper.getAcroFields(); HashMap PDFFields = acroFields.getFields(); for (Iterator it = PDFFields.keySet().iterator(); it.hasNext();) { Object object = it.next(); String keyt = String.valueOf(object); if (getData().get(keyt) != null) { Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]"); if (!keyt.startsWith("image")) { acroFields.setField(keyt, String.valueOf(getData().get(keyt))); } else { setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage()); } } if (getData().get(keyt.replace("_", ".")) != null) { Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]"); if (!keyt.startsWith("image")) { acroFields.setField(keyt, String.valueOf(getData().get(keyt.replace("_", ".")))); } else { setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage()); } } } Log.Debug(this, "Looking for tables in: " + getName()); for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) { String key = it.next(); if (key.contains(TableHandler.KEY_TABLE)) {//Table found @SuppressWarnings("unchecked") List<String[]> value = (List<String[]>) getData().get(key); for (int i = 0; i < value.size(); i++) { String[] strings = value.get(i); if (getTemplate() != null) { strings = refactorRow(getTemplate(), strings); } for (int j = 0; j < strings.length; j++) { String cellValue = strings[j]; String fieldname = "col" + j + "row" + i; Log.Debug(this, "Filling Field: " + fieldname + " [" + getData().get(cellValue) + "]"); acroFields.setField(fieldname, cellValue); } } } } pdfStamper.close(); Log.Debug(this, "Done file: " + getTarget().getPath()); } catch (Exception ex) { Log.Debug(ex); } }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Returns the text of a given PDF as {@link String}. * //from w w w. java2s . com * @param file * input as PDF * @return text of the given PDF * @throws IOException * @see File * @since 0.9.3 */ public static String getText(final File file) throws IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(file)); if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } final PdfReader pdfReader = new PdfReader(file.getAbsolutePath()); final PdfTextExtractor pdfExtractor = new PdfTextExtractor(pdfReader); final StringBuilder sb = new StringBuilder(); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { sb.append(pdfExtractor.getTextFromPage(page)); sb.append(HelperString.NEW_LINE); } final String result = sb.toString(); if (log.isDebugEnabled()) log.debug(HelperLog.methodExit(result)); return result; }
From source file:net.laubenberger.bogatyr.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"); * /* www . j av a 2 s . c om*/ * @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.7.0 */ @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$ } PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(source.getAbsolutePath()); stamper = new PdfStamper(reader, new FileOutputStream(dest)); final HashMap<String, String> info = reader.getInfo(); info.putAll(metadata); stamper.setMoreInfo(info); } finally { if (null != stamper) { stamper.close(); } if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Returns the metadata of a given PDF as {@link Map}. * //ww w .j a v a 2 s . c o m * @param file * input as PDF * @return {@link Map} containinfg the metadata of the given PDF * @throws IOException * @see File * @since 0.9.4 */ @SuppressWarnings("unchecked") public static Map<String, String> getMetaData(final File file) throws IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(file)); if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } PdfReader reader = null; Map<String, String> result; try { reader = new PdfReader(file.getAbsolutePath()); result = reader.getInfo(); } finally { if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit(result)); return result; }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Encrypt a PDF with a given user and password. * /* ww w . j a v a 2s. c om*/ * @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.9.4 */ 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; OutputStream os = null; try { reader = new PdfReader(source.getAbsolutePath()); os = new FileOutputStream(dest); 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 != os) { os.close(); } if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Adds a all restrictions to a PDF with a given password. * // ww w .j a va 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.9.4 */ 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; OutputStream os = null; try { reader = new PdfReader(source.getAbsolutePath()); os = new FileOutputStream(dest); PdfEncryptor.encrypt(reader, os, null, password, 0, true); } finally { if (null != os) { os.close(); } if (null != reader) { reader.close(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }