List of usage examples for com.lowagie.text.pdf SimpleBookmark getBookmark
public static List getBookmark(PdfReader reader)
List
with the bookmarks. From source file:lucee.runtime.tag.PDF.java
License:Open Source License
private void doActionAddWatermark() throws PageException, IOException, DocumentException { required("pdf", "addWatermark", "source", source); if (copyFrom == null && image == null) throw new ApplicationException( "at least one of the following attributes must be defined " + "[copyFrom,image]"); if (destination != null && destination.exists() && !overwrite) throw new ApplicationException("destination file [" + destination + "] already exists"); // image// w w w . java2s .co m Image img = null; if (image != null) { lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext, image, false, false, true, null); img = Image.getInstance(ri.getBufferedImage(), null, false); } // copy From else { byte[] barr; try { Resource res = Caster.toResource(pageContext, copyFrom, true); barr = IOUtil.toBytes(res); } catch (ExpressionException ee) { barr = Caster.toBinary(copyFrom); } img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false); } // position float x = UNDEFINED, y = UNDEFINED; if (!StringUtil.isEmpty(position)) { int index = position.indexOf(','); if (index == -1) throw new ApplicationException("attribute [position] has an invalid value [" + position + "]," + "value should follow one of the following pattern [40,50], [40,] or [,50]"); String strX = position.substring(0, index).trim(); String strY = position.substring(index + 1).trim(); if (!StringUtil.isEmpty(strX)) x = Caster.toIntValue(strX); if (!StringUtil.isEmpty(strY)) y = Caster.toIntValue(strY); } PDFDocument doc = toPDFDocument(source, password, null); doc.setPages(pages); PdfReader reader = doc.getPdfReader(); reader.consolidateNamedDestinations(); boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); java.util.List bookmarks = SimpleBookmark.getBookmark(reader); ArrayList master = new ArrayList(); if (bookmarks != null) master.addAll(bookmarks); // output OutputStream os = null; if (!StringUtil.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } try { int len = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); if (len > 0) { if (x == UNDEFINED || y == UNDEFINED) { PdfImportedPage first = stamp.getImportedPage(reader, 1); if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2; if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2; } img.setAbsolutePosition(x, y); //img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte } // rotation if (rotation != 0) { img.setRotationDegrees(rotation); } Set _pages = doc.getPages(); for (int i = 1; i <= len; i++) { if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue; PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i); PdfGState gs1 = new PdfGState(); //print.out("op:"+opacity); gs1.setFillOpacity(opacity); //gs1.setStrokeOpacity(opacity); cb.setGState(gs1); cb.addImage(img); } if (bookmarks != null) stamp.setOutlines(master); stamp.close(); } finally { IOUtil.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true);// MUST overwrite if (!StringUtil.isEmpty(name)) { pageContext.setVariable(name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password)); } } } }
From source file:lucee.runtime.tag.PDF.java
License:Open Source License
private void doActionRemoveWatermark() throws PageException, IOException, DocumentException { required("pdf", "removeWatermark", "source", source); if (destination != null && destination.exists() && !overwrite) throw new ApplicationException("destination file [" + destination + "] already exists"); lucee.runtime.img.Image ri = new lucee.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK); Image img = Image.getInstance(ri.getBufferedImage(), null, false); img.setAbsolutePosition(1, 1);//from ww w . j a va 2s. c o m PDFDocument doc = toPDFDocument(source, password, null); doc.setPages(pages); PdfReader reader = doc.getPdfReader(); boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); java.util.List bookmarks = SimpleBookmark.getBookmark(reader); ArrayList master = new ArrayList(); if (bookmarks != null) master.addAll(bookmarks); // output OutputStream os = null; if (!StringUtil.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } try { int len = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); Set _pages = doc.getPages(); for (int i = 1; i <= len; i++) { if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue; PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i); PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(0); cb.setGState(gs1); cb.addImage(img); } if (bookmarks != null) stamp.setOutlines(master); stamp.close(); } finally { IOUtil.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true);// MUST overwrite if (!StringUtil.isEmpty(name)) { pageContext.setVariable(name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password)); } } } }
From source file:lucee.runtime.text.pdf.PDFUtil.java
License:Open Source License
/** * @param docs//from w w w. j a v a2s . c o 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();//from w w w.j a va 2 s . c om 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(); 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.sqs2.omr.master.pdfbookmark.PDFtoBookmarkTranslator.java
License:Apache License
@Override public void execute(InputStream sourceInputStream, String systemId, OutputStream bookmarkOutputStream, URIResolver uriResolver) throws InvalidPageMasterException { try {//from w w w . ja v a 2 s . c om PdfReader reader = new PdfReader(sourceInputStream); this.numPages = reader.getNumberOfPages(); SimpleBookmark.exportToXML(SimpleBookmark.getBookmark(reader), bookmarkOutputStream, "UTF-8", false); reader.close(); } catch (IOException ex) { throw new InvalidPageMasterException(); } 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 //from w w w. ja v a 2 s.c o m * @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(); }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void extractPagesToNewPDF(SavePDF current_selection) { final boolean exportIntoMultiplePages = current_selection.getExportType(); final int[] pgsToExport = current_selection.getExportPages(); if (pgsToExport == null) return;/*w w w . j a v a 2 s .c om*/ final int noOfPages = pgsToExport.length; // get user choice final String output_dir = current_selection.getRootDir() + separator + fileName + separator + "PDFs" + separator; File testDirExists = new File(output_dir); if (!testDirExists.exists()) testDirExists.mkdirs(); final ProgressMonitor status = new ProgressMonitor(currentGUI.getFrame(), Messages.getMessage("PdfViewerMessage.GeneratingPdfs"), "", 0, noOfPages); final SwingWorker worker = new SwingWorker() { public Object construct() { if (exportIntoMultiplePages) { boolean yesToAll = false; for (int i = 0; i < noOfPages; i++) { int page = pgsToExport[i]; if (status.isCanceled()) { currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") + i + " " + Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported")); return null; } try { PdfReader reader = new PdfReader(selectedFile); File fileToSave = new File(output_dir + fileName + "_pg_" + page + ".pdf"); if (fileToSave.exists() && !yesToAll) { if (pgsToExport.length > 1) { int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), true); if (n == 0) { // clicked yes so just carry on for this // once } else if (n == 1) { // clicked yes to all, so set flag yesToAll = true; } else if (n == 2) { // clicked no, so loop round again status.setProgress(page); continue; } else { currentGUI.showMessageDialog( Messages.getMessage("PdfViewerError.UserStoppedExport") + i + " " + Messages.getMessage( "PdfViewerError.ReportNumberOfPagesExported")); status.close(); return null; } } else { int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), false); if (n == 0) { // clicked yes so just carry on } else { // clicked no, so exit return null; } } } Document document = new Document(); PdfCopy writer = new PdfCopy(document, new FileOutputStream(fileToSave)); document.open(); PdfImportedPage pip = writer.getImportedPage(reader, page); writer.addPage(pip); PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } document.close(); } catch (Exception de) { de.printStackTrace(); } status.setProgress(i + 1); } } else { try { PdfReader reader = new PdfReader(selectedFile); File fileToSave = new File(output_dir + "export_" + fileName + ".pdf"); if (fileToSave.exists()) { int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(), false); if (n == 0) { // clicked yes so just carry on } else { // clicked no, so exit return null; } } Document document = new Document(); PdfCopy copy = new PdfCopy(document, new FileOutputStream(fileToSave.getAbsolutePath())); document.open(); PdfImportedPage pip; for (int i = 0; i < noOfPages; i++) { int page = pgsToExport[i]; pip = copy.getImportedPage(reader, page); copy.addPage(pip); } PRAcroForm form = reader.getAcroForm(); if (form != null) { copy.copyAcroForm(reader); } List bookmarks = SimpleBookmark.getBookmark(reader); copy.setOutlines(bookmarks); document.close(); } catch (Exception de) { de.printStackTrace(); } } status.close(); currentGUI.showMessageDialog( Messages.getMessage("PdfViewerMessage.PagesSavedAsPdfTo") + " " + output_dir); return null; } }; worker.start(); }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void delete(int pageCount, PdfPageData currentPageData, DeletePDFPages deletedPages) { File tempFile = null;/*from ww w . j av a 2 s . c o m*/ try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToDelete = deletedPages.getDeletedPages(); if (pgsToDelete == null) return; int check = -1; if (pgsToDelete.length == 1) { check = currentGUI.showConfirmDialog(Messages.getMessage("PdfViewerMessage.ConfirmDeletePage"), Messages.getMessage("PdfViewerMessage.Confirm"), JOptionPane.YES_NO_OPTION); } else { check = currentGUI.showConfirmDialog(Messages.getMessage("PdfViewerMessage.ConfirmDeletePage"), Messages.getMessage("PdfViewerMessage.Confirm"), JOptionPane.YES_NO_OPTION); } if (check != 0) return; if (pgsToDelete == null) return; List pagesToDelete = new ArrayList(); for (int i = 0; i < pgsToDelete.length; i++) pagesToDelete.add(new Integer(pgsToDelete[i])); PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); List bookmarks = SimpleBookmark.getBookmark(reader); // int[][] xx = new int[pgsToDelete.length][1]; // for(int i=0; i<pgsToDelete.length;i++){ // xx[i][0] = pgsToDelete[i]; // } // // PageRanges pr = new PageRanges(xx); // int[] toRemove = linearize(pr.getMembers()); // // SimpleBookmark.eliminatePages(bookmarks,toRemove); SimpleBookmark.shiftPageNumbers(bookmarks, -1, new int[] { 5, 5 }); // if(1==1) // return; /** * check document will have at leat 1 page */ boolean pageAdded = false; for (int page = 1; page <= pageCount; page++) { if (!pagesToDelete.contains(new Integer(page))) { pageAdded = true; page = pageCount; } } if (!pageAdded) { currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.PageWillNotDelete")); return; } Document document = new Document(); PdfCopy writer = new PdfCopy(document, new FileOutputStream(selectedFile)); document.open(); for (int page = 1; page <= pageCount; page++) { if (!pagesToDelete.contains(new Integer(page))) { PdfImportedPage pip = writer.getImportedPage(reader, page); writer.addPage(pip); pageAdded = true; } } writer.setOutlines(bookmarks); document.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.jrimum.bopepo.pdf.PDFUtil.java
License:Apache License
/** * <p>/* w w w . jav a2 s . c o m*/ * Junta varios arquivos pdf em um soh. * </p> * * @param pdfFiles * Lista de array de bytes * * @return Arquivo PDF em forma de byte * @since 0.2 */ @SuppressWarnings("unchecked") public static byte[] mergeFiles(List<byte[]> pdfFiles) { // retorno byte[] bytes = null; if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) { int pageOffset = 0; boolean first = true; ArrayList master = null; Document document = null; PdfCopy writer = null; ByteArrayOutputStream byteOS = null; try { byteOS = new ByteArrayOutputStream(); master = new ArrayList(); for (byte[] doc : pdfFiles) { if (isNotNull(doc)) { // cria-se um reader para cada documento PdfReader reader = new PdfReader(doc); if (reader.isEncrypted()) { reader = new PdfReader(doc, "".getBytes()); } reader.consolidateNamedDestinations(); // pega-se o numero total de paginas int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (isNotNull(bookmarks)) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += n; if (first) { // passo 1: criar um document-object document = new Document(reader.getPageSizeWithRotation(1)); // passo 2: criar um writer que observa o documento writer = new PdfCopy(document, byteOS); document.addAuthor("JRimum Group"); document.addSubject("JRimum Merged Document"); document.addCreator("JRimum Utilix"); // passo 3: abre-se o documento document.open(); first = false; } // passo 4: adciona-se o conteudo PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } } } if (master.size() > 0) { writer.setOutlines(master); } // passo 5: fecha-se o documento if (isNotNull(document)) { document.close(); } bytes = byteOS.toByteArray(); } catch (Exception e) { LOG.error("", e); } } return bytes; }
From source file:org.kuali.ext.mm.document.web.struts.CountWorksheetPrintAction.java
License:Educational Community License
private void combineAndFlushReportPDFFiles(List<File> fileList, HttpServletRequest request, HttpServletResponse response) throws Exception { long startTime = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ArrayList master = new ArrayList(); int pageOffset = 0; int f = 0;//from w w w.j a v a 2 s . com PdfCopy writer = null; com.lowagie.text.Document document = null; for (File file : fileList) { // we create a reader for a certain document String reportName = file.getAbsolutePath(); PdfReader reader = new PdfReader(reportName); 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 (f == 0) { // step 1: creation of a document-object document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, baos); // 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); } writer.freeReader(reader); f++; } if (!master.isEmpty()) writer.setOutlines(master); // step 5: we close the document document.close(); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } sbContentDispValue.append("; filename="); sbContentDispValue.append(MMUtil.getFileName()); String contentDisposition = sbContentDispValue.toString(); response.setContentType("application/pdf"); response.setHeader("Content-disposition", contentDisposition); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setContentLength(baos.size()); // write to output ServletOutputStream sos = response.getOutputStream(); baos.writeTo(sos); sos.flush(); baos.close(); sos.close(); long endTime = System.currentTimeMillis(); loggerAc.debug("Time taken for report Parameter settings in action " + (endTime - startTime)); }