List of usage examples for com.lowagie.text.pdf PdfReader getPageSizeWithRotation
public Rectangle getPageSizeWithRotation(PdfDictionary page)
From source file:lucee.runtime.text.pdf.PDFUtil.java
License:Open Source License
/** * @param docs// w w w . ja v a 2s. co m * @param os * @param removePages if true, pages defined in PDFDocument will be removed, otherwise all other pages will be removed * @param version * @throws PageException * @throws IOException * @throws DocumentException */ public static void concat(PDFDocument[] docs, OutputStream os, boolean keepBookmark, boolean removePages, boolean stopOnError, char version) throws PageException, IOException, DocumentException { Document document = null; PdfCopy writer = null; PdfReader reader; Set pages; boolean isInit = false; PdfImportedPage page; try { int pageOffset = 0; ArrayList master = new ArrayList(); for (int i = 0; i < docs.length; i++) { // we create a reader for a certain document pages = docs[i].getPages(); try { reader = docs[i].getPdfReader(); } catch (Throwable t) { if (!stopOnError) continue; throw Caster.toPageException(t); } reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); List bookmarks = keepBookmark ? SimpleBookmark.getBookmark(reader) : null; if (bookmarks != null) { removeBookmarks(bookmarks, pages, removePages); if (pageOffset != 0) SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); master.addAll(bookmarks); } if (!isInit) { isInit = true; document = new Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, os); if (version != 0) writer.setPdfVersion(version); document.open(); } for (int y = 1; y <= n; y++) { if (pages != null && removePages == pages.contains(Integer.valueOf(y))) { continue; } pageOffset++; page = writer.getImportedPage(reader, y); writer.addPage(page); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); } if (master.size() > 0) writer.setOutlines(master); } finally { IOUtil.closeEL(document); } }
From source file:lucee.runtime.text.pdf.PDFUtil.java
License:Open Source License
public static void encrypt(PDFDocument doc, OutputStream os, String newUserPassword, String newOwnerPassword, int permissions, int encryption) throws ApplicationException, DocumentException, IOException { byte[] user = newUserPassword == null ? null : newUserPassword.getBytes(); byte[] owner = newOwnerPassword == null ? null : newOwnerPassword.getBytes(); PdfReader pr = doc.getPdfReader(); List bookmarks = SimpleBookmark.getBookmark(pr); int n = pr.getNumberOfPages(); Document document = new Document(pr.getPageSizeWithRotation(1)); PdfCopy writer = new PdfCopy(document, os); if (encryption != ENCRYPT_NONE) writer.setEncryption(user, owner, permissions, encryption); document.open();//from w ww .j a v a 2s . c o m PdfImportedPage page; for (int i = 1; i <= n; i++) { page = writer.getImportedPage(pr, i); writer.addPage(page); } PRAcroForm form = pr.getAcroForm(); if (form != null) writer.copyAcroForm(pr); if (bookmarks != null) writer.setOutlines(bookmarks); document.close(); }
From source file:net.sf.jsignpdf.PdfExtraInfo.java
License:Mozilla Public License
/** * Returns page info.//from ww w . jav a 2 s .c o m * * @param aPage * number of page for which size should be returned * @return FloatPoint or null */ public PageInfo getPageInfo(int aPage) { PageInfo tmpResult = null; PdfReader reader = null; try { reader = PdfUtils.getPdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes()); final Rectangle tmpRect = reader.getPageSizeWithRotation(aPage); if (tmpRect != null) { tmpResult = new PageInfo(tmpRect.getRight(), tmpRect.getTop()); } } catch (Exception e) { // nothing to do } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } return tmpResult; }
From source file:net.sourceforge.fenixedu.util.report.ReportsUtils.java
License:Open Source License
static public byte[] stampPdfAt(byte[] originalPdf, byte[] toStampPdf, int positionX, int positionY) { try {/* www . ja v a 2 s.c om*/ PdfReader originalPdfReader = new PdfReader(originalPdf); PdfReader toStampPdfReader = new PdfReader(toStampPdf); ByteArrayOutputStream stream = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper(originalPdfReader, stream); PdfImportedPage importedPage = stamper.getImportedPage(toStampPdfReader, 1); PdfContentByte overContent = stamper.getOverContent(1); Rectangle pageSizeWithRotation = originalPdfReader.getPageSizeWithRotation(1); Rectangle pageSizeWithRotationStamper = toStampPdfReader.getPageSizeWithRotation(1); logger.info( String.format("[ %s, %s]", pageSizeWithRotation.getWidth(), pageSizeWithRotation.getHeight())); logger.info(String.format("[ %s, %s]", pageSizeWithRotationStamper.getWidth(), pageSizeWithRotationStamper.getHeight())); Image image = Image.getInstance(importedPage); overContent.addImage(image, image.getWidth(), 0f, 0f, image.getHeight(), positionX, positionY); stamper.close(); originalPdfReader.close(); toStampPdfReader.close(); return stream.toByteArray(); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:org.adempiere.webui.apps.AEnv.java
License:Open Source License
/** * * @param pdfList/* w w w. j av a 2s . co m*/ * @param outFile * @throws IOException * @throws DocumentException * @throws FileNotFoundException */ public static void mergePdf(List<File> pdfList, File outFile) throws IOException, DocumentException, FileNotFoundException { Document document = null; PdfWriter copy = null; for (File f : pdfList) { PdfReader reader = new PdfReader(f.getAbsolutePath()); if (document == null) { document = new Document(reader.getPageSizeWithRotation(1)); copy = PdfWriter.getInstance(document, new FileOutputStream(outFile)); document.open(); } int pages = reader.getNumberOfPages(); PdfContentByte cb = copy.getDirectContent(); for (int i = 1; i <= pages; i++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, i); cb.addTemplate(page, 0, 0); } } document.close(); }
From source file:org.adempiere.webui.apps.ProcessDialog.java
License:Open Source License
public void onPrintShipments() { // Loop through all items List<File> pdfList = new ArrayList<File>(); for (int i = 0; i < m_ids.length; i++) { int M_InOut_ID = m_ids[i]; ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.SHIPMENT, M_InOut_ID); pdfList.add(re.getPDF());/* w ww .j a v a2 s. co m*/ } if (pdfList.size() > 1) { try { File outFile = File.createTempFile("PrintShipments", ".pdf"); Document document = null; PdfWriter copy = null; for (File f : pdfList) { String fileName = f.getAbsolutePath(); PdfReader reader = new PdfReader(fileName); reader.consolidateNamedDestinations(); if (document == null) { document = new Document(reader.getPageSizeWithRotation(1)); copy = PdfWriter.getInstance(document, new FileOutputStream(outFile)); document.open(); } int pages = reader.getNumberOfPages(); PdfContentByte cb = copy.getDirectContent(); for (int i = 1; i <= pages; i++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, i); cb.addTemplate(page, 0, 0); } } document.close(); hideBusyDialog(); Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile)); SessionManager.getAppDesktop().showWindow(win, "center"); } catch (Exception e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } } else if (pdfList.size() > 0) { hideBusyDialog(); try { Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0))); SessionManager.getAppDesktop().showWindow(win, "center"); } catch (Exception e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } } }
From source file:org.adempiere.webui.apps.ProcessDialog.java
License:Open Source License
public void onPrintInvoices() { // Loop through all items List<File> pdfList = new ArrayList<File>(); for (int i = 0; i < m_ids.length; i++) { int C_Invoice_ID = m_ids[i]; ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.INVOICE, C_Invoice_ID); pdfList.add(re.getPDF());//w ww. j a va 2s . c o m } if (pdfList.size() > 1) { try { File outFile = File.createTempFile("PrintInvoices", ".pdf"); Document document = null; PdfWriter copy = null; for (File f : pdfList) { PdfReader reader = new PdfReader(f.getAbsolutePath()); if (document == null) { document = new Document(reader.getPageSizeWithRotation(1)); copy = PdfWriter.getInstance(document, new FileOutputStream(outFile)); document.open(); } PdfContentByte cb = copy.getDirectContent(); // Holds the PDF int pages = reader.getNumberOfPages(); for (int i = 1; i <= pages; i++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, i); cb.addTemplate(page, 0, 0); } } document.close(); hideBusyDialog(); Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile)); SessionManager.getAppDesktop().showWindow(win, "center"); } catch (Exception e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } } else if (pdfList.size() > 0) { try { Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0))); SessionManager.getAppDesktop().showWindow(win, "center"); } catch (Exception e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } } }
From source file:org.alchemy.core.AlcSession.java
License:Open Source License
/** Adds a pdfReadPage to an existing pdf file * // w w w. j a v a 2s . c o m * @param mainPdf The main pdf with multiple pages. * Also used as the destination file. * @param tempPdf The 'new' pdf with one pdfReadPage to be added to the main pdf * @return */ boolean addPageToPdf(File mainPdf, File tempPdf) { try { // Destination file created in the temp dir then we will move it File dest = new File(DIR_TEMP, "Alchemy.pdf"); OutputStream output = new FileOutputStream(dest); PdfReader reader = new PdfReader(mainPdf.getPath()); PdfReader newPdf = new PdfReader(tempPdf.getPath()); // See if the size of the canvas has increased // Size of the most recent temp PDF com.lowagie.text.Rectangle currentSize = newPdf.getPageSizeWithRotation(1); // Size of the session pdf at present com.lowagie.text.Rectangle oldSize = reader.getPageSizeWithRotation(1); // Sizes to be used from now on float pdfWidth = oldSize.getWidth(); float pdfHeight = oldSize.getHeight(); if (currentSize.getWidth() > pdfWidth) { pdfWidth = currentSize.getWidth(); } if (currentSize.getHeight() > pdfHeight) { pdfHeight = currentSize.getHeight(); } // Use the new bigger canvas size if required com.lowagie.text.Document document = new com.lowagie.text.Document( new com.lowagie.text.Rectangle(pdfWidth, pdfHeight), 0, 0, 0, 0); PdfCopy copy = new PdfCopy(document, output); // Copy the meta data document.addTitle("Alchemy Session"); document.addAuthor(USER_NAME); document.addCreator("Alchemy <http://al.chemy.org>"); copy.setXmpMetadata(reader.getMetadata()); document.open(); // Holds the PDF PdfContentByte cb = copy.getDirectContent(); // Add each page from the main PDF for (int i = 0; i < reader.getNumberOfPages();) { ++i; document.newPage(); cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB); PdfImportedPage page = copy.getImportedPage(reader, i); copy.addPage(page); } // Add the last (new) page document.newPage(); PdfImportedPage lastPage = copy.getImportedPage(newPdf, 1); copy.addPage(lastPage); output.flush(); document.close(); output.close(); if (dest.exists()) { // Save the location of the main pdf String mainPdfPath = mainPdf.getPath(); // Delete the old file if (mainPdf.exists()) { mainPdf.delete(); } // The final joined up pdf file File joinPdf = new File(mainPdfPath); // Rename the file boolean success = dest.renameTo(joinPdf); if (!success) { System.err.println("Error moving Pdf"); return false; } } else { System.err.println("File does not exist?!: " + dest.getAbsolutePath()); return false; } return true; } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java
License:Open Source License
/** * construct a pdf document from pdf parts. * //from w ww. ja v a2 s . com * @param files * list containing the pdf to assemble * @param properties * converter properties * @param fout * outputstream to write the new pdf * @param base_url * base url of the document * @param producer * producer of the pdf * * @throws CConvertException * if an error occured while reconstruct. */ public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } // end if else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; // step 1: creation of a document-object // set title/creator/author document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, out); // use pdf version 1.5 writer.setPdfVersion(PdfWriter.VERSION_1_3); // compress the pdf writer.setFullCompression(); // check if encryption is needed if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType); } // end if final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } // end if else if (base_url != null) { document.addTitle(base_url); } // end else if final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } // end if else { document.addCreator(IHtmlToPdfTransformer.VERSION); } // end else final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } // end if final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.add(new Meta("Producer", sproducer)); } // end if else { document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer))); } // end else // step 3: we open the document document.open(); } // end if PdfImportedPage page; for (int j = 0; j < n;) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } // end for } // end for document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext();) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i) .replaceAll("<pagecount>", "" + n); // text over the existing page final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false" .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } // end if else { reader = new PdfReader(tmp2.getAbsolutePath()); } // end else final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } // end if final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } // end if else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } // end else if (reason != null) { sap.setReason(reason); } // end if if (location != null) { sap.setLocation(location); } // end if stp.close(); oldOut.flush(); } // end if } // end try catch (final Exception e) { throw new CConvertException( "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } // end catch finally { try { tmp.delete(); } // end try catch (final Exception ignore) { } try { tmp2.delete(); } // end try catch (final Exception ignore) { } } // end finally }
From source file:org.jaffa.modules.printing.services.MultiFormPrintEngine.java
License:Open Source License
/** * Merge a list of generated Pdf Documents together * @param documents /*www .j ava 2s .c om*/ * @throws java.io.IOException * @throws com.lowagie.text.DocumentException * @return byte[] */ public static byte[] mergePdf(List<byte[]> documents) throws IOException, DocumentException { int pageOffset = 0; ArrayList master = new ArrayList(); ByteArrayOutputStream output = new ByteArrayOutputStream(); Document document = null; PdfCopy writer = null; boolean first = true; for (Iterator<byte[]> it = documents.iterator(); it.hasNext();) { // we create a reader for a certain document PdfReader reader = new PdfReader(it.next()); reader.consolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); master.addAll(bookmarks); } pageOffset += n; if (first) { first = false; // step 1: creation of a document-object document = new Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, output); // step 3: we open the document document.open(); } // step 4: we add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); } if (master.size() > 0) writer.setOutlines(master); // step 5: we close the document if (document != null) document.close(); return output.toByteArray(); }