List of usage examples for com.lowagie.text.pdf PdfReader PdfReader
public PdfReader(PdfReader reader)
From source file:org.ghost4j.document.PDFDocument.java
License:LGPL
public int getPageCount() throws DocumentException { int pageCount = 0; if (content == null) { return pageCount; }// ww w . jav a2s .c o m ByteArrayInputStream bais = null; PdfReader reader = null; try { bais = new ByteArrayInputStream(content); reader = new PdfReader(bais); pageCount = reader.getNumberOfPages(); } catch (Exception e) { throw new DocumentException(e); } finally { if (reader != null) reader.close(); IOUtils.closeQuietly(bais); } return pageCount; }
From source file:org.ghost4j.document.PDFDocument.java
License:LGPL
public Document extract(int begin, int end) throws DocumentException { this.assertValidPageRange(begin, end); PDFDocument result = new PDFDocument(); ByteArrayInputStream bais = null; ByteArrayOutputStream baos = null; if (content != null) { com.lowagie.text.Document document = new com.lowagie.text.Document(); try {/*from w w w . j ava 2s . c om*/ bais = new ByteArrayInputStream(content); baos = new ByteArrayOutputStream(); PdfReader inputPDF = new PdfReader(bais); // create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; while (begin <= end) { document.newPage(); page = writer.getImportedPage(inputPDF, begin); cb.addTemplate(page, 0, 0); begin++; } document.close(); result.load(new ByteArrayInputStream(baos.toByteArray())); } catch (Exception e) { throw new DocumentException(e); } finally { if (document.isOpen()) document.close(); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(baos); } } return result; }
From source file:org.ghost4j.document.PDFDocument.java
License:LGPL
@Override public void append(Document document) throws DocumentException { super.append(document); ByteArrayOutputStream baos = null; com.lowagie.text.Document mergedDocument = new com.lowagie.text.Document(); try {//from ww w .j av a2s .c o m baos = new ByteArrayOutputStream(); PdfCopy copy = new PdfCopy(mergedDocument, baos); mergedDocument.open(); // copy current document PdfReader reader = new PdfReader(content); int pageCount = reader.getNumberOfPages(); for (int i = 0; i < pageCount;) { copy.addPage(copy.getImportedPage(reader, ++i)); } // copy new document reader = new PdfReader(document.getContent()); pageCount = reader.getNumberOfPages(); for (int i = 0; i < pageCount;) { copy.addPage(copy.getImportedPage(reader, ++i)); } mergedDocument.close(); // replace content with new content content = baos.toByteArray(); } catch (Exception e) { throw new DocumentException(e); } finally { if (mergedDocument.isOpen()) mergedDocument.close(); IOUtils.closeQuietly(baos); } }
From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java
License:Open Source License
/** * Process the template and do the following * <ol>/*w w w . j a v a 2 s . co m*/ * <li>Throw errors if there is something wrong with the template (in getTemplateName()) * <li>Determine to the total number of pages in the template * (The template should have at least one page) * <li>Populate an array where each template page should have one entry in it. * Each entry will a PageDetails object, containing a list of fields * on the page, and a list of repeating entities. * </ol> * On return from this the engine will calculate the total no of template pages, * and the unique list of reappearing group names * @throws FormPrintException Thrown if there is an error parsing the template pdf * @return This returns a List of PageDetails objects which contain data about * each page. It is assumed that the size of the list indicated the * number of pages in the template document being used */ protected List parseTemplatePages() throws FormPrintException { log.debug("parseTemplatePages:"); try { m_templateReader = new PdfReader(getTemplateName()); } catch (IOException e) { log.error("Error opening template - " + e.getMessage(), e); throw new EngineProcessingException("Error opening template - " + e.getMessage()); } // we retrieve the total number of pages int templatePages = m_templateReader.getNumberOfPages(); if (templatePages < 1) throw new EngineProcessingException("Template Document has no pages!"); if (log.isDebugEnabled()) log.debug("Template '" + getTemplateName() + "' has " + templatePages + " page(s)"); // Create Empty array of page data ArrayList pageData = new ArrayList(); for (int templatePage = 0; templatePage < templatePages; templatePage++) { PageDetailsExtended page = new PageDetailsExtended(); pageData.add(page); } // Look for a related data file... File data = new File(getTemplateName() + ".csv"); if (!data.exists()) { log.warn("CSV Parse Error: No data file found for field layout"); } else { // Read the file, and populate PageDetailsExtended try (BufferedReader in = new BufferedReader(new FileReader(data))) { String line; int[] colOrder = null; int row = 0; while ((line = in.readLine()) != null) { row++; if (line.startsWith("#") || line.length() == 0) // ignore commented out or blank lines. continue; String[] cols = line.split(","); if (row == 1) { // Must be first line, analyse column names.... colOrder = new int[cols.length]; for (int i = 0; i < cols.length; i++) { String col = cols[i]; colOrder[i] = HEADINGS.indexOf(col); if (colOrder[i] == -1) { log.error("CSV Parse Error: Unknown column heading '" + col + "' in column " + (i + 1) + ". Can't Process File"); throw new EngineProcessingException( "Can't read layout data file, column headings incorrect"); } } } else { // This is a row of data, process it int pageNo = 0; String field = null; FormPrintEngineIText.FieldProperties props = new FormPrintEngineIText.FieldProperties(); for (int i = 0; i < cols.length; i++) { try { if (cols[i] != null && cols[i].trim().length() > 0 && colOrder != null) { String value = cols[i].trim(); switch (colOrder[i]) { case COLUMN_PAGE: pageNo = Integer.parseInt(value); break; case COLUMN_FIELD: field = value; break; case COLUMN_X1: props.x1 = Float.parseFloat(value); break; case COLUMN_Y1: props.y1 = Float.parseFloat(value); break; case COLUMN_X2: props.x2 = Float.parseFloat(value); break; case COLUMN_Y2: props.y2 = Float.parseFloat(value); break; case COLUMN_FONT: props.fontFace = value; break; case COLUMN_SIZE: props.fontSize = Float.parseFloat(value); break; case COLUMN_ALIGN: if ("center".equalsIgnoreCase(value)) { props.align = Element.ALIGN_CENTER; } else if ("right".equalsIgnoreCase(value)) { props.align = Element.ALIGN_RIGHT; } break; case COLUMN_MULTILINE: props.multiLine = Boolean.valueOf(value).booleanValue(); break; case COLUMN_FIT_METHOD: if (FIT_METHODS.contains(value.toLowerCase())) props.fitMethod = FIT_METHODS.indexOf(value.toLowerCase()); break; case COLUMN_ROTATE: props.rotate = Float.parseFloat(value); break; case COLUMN_STYLE: props.style = value; break; case COLUMN_COLOR: props.color = value; break; case COLUMN_BACKGROUND: props.background = value; break; case COLUMN_SAMPLE_DATA: props.sampleData = URLDecoder.decode(value, "UTF-8"); break; case COLUMN_OPACITY: props.opacity = Float.parseFloat(value); break; } // switch } } catch (NumberFormatException ne) { String err = "CSV Parse Error: Invalid Numeric Value in Form Layout Data. Row=" + row + ", Column=" + i + ", Value='" + cols[i] + "'"; log.error(err); throw new EngineProcessingException(err); } } // for if (pageNo < 1 || pageNo > templatePages) { String err = "CSV Parse Error: Invalid Page Number " + pageNo + " on row " + row; log.error(err); throw new EngineProcessingException(err); } if (field == null) { String err = "CSV Parse Error: Invalid/Missing Field Name on row " + row; log.error(err); throw new EngineProcessingException(err); } PageDetailsExtended page = (PageDetailsExtended) pageData.get(pageNo - 1); page.fieldList.add(field); page.fieldProperties.put(field, props); } } // while loop on each input line } catch (IOException e) { log.warn("CSV Parse Error: Failed to read layout data file", e); } } return pageData; }
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 www .j a v a 2s . 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.jaffa.modules.printing.services.PdfHelper.java
License:Open Source License
/** * Scale the pages of the input pdfOutput document to the given pageSize. * @param pdfOutput The PDF document to rescale, in the form of a ByteArrayOutputStream. * @param pageSize The new page size to which to scale to PDF document, e.g. "A4". * @param noEnlarge If true, center pages instead of enlarging them. * Use noEnlarge if the new page size is larger than the old one * and the pages should be centered instead of enlarged. * @param preserveAspectRatio If true, the aspect ratio will be preserved. * @return The PDF document with its pages scaled to the input pageSize. */// www . j a va2 s . c om public static byte[] scalePdfPages(byte[] pdfOutput, String pageSize, boolean noEnlarge, boolean preserveAspectRatio) throws FormPrintException { if (pageSize == null || pdfOutput == null) { return pdfOutput; } // Get the dimensions of the given pageSize in PostScript points. // A PostScript point is a 72th of an inch. float dimX; float dimY; Rectangle rectangle; try { rectangle = PageSize.getRectangle(pageSize); } catch (Exception ex) { FormPrintException e = new PdfProcessingException( "scalePdfPages - Invalid page size = " + pageSize + " "); log.error(" scalePdfPages - Invalid page size: " + pageSize + ". " + ex.getMessage() + ". "); throw e; } if (rectangle != null) { dimX = rectangle.getWidth(); dimY = rectangle.getHeight(); } else { FormPrintException e = new PdfProcessingException("scalePdfPages - Invalid page size: " + pageSize); log.error(" scalePdfPages - Invalid page size: " + pageSize); throw e; } //Create portrait and landscape rectangles for the given page size. Rectangle portraitPageSize; Rectangle landscapePageSize; if (dimY > dimX) { portraitPageSize = new Rectangle(dimX, dimY); landscapePageSize = new Rectangle(dimY, dimX); } else { portraitPageSize = new Rectangle(dimY, dimX); landscapePageSize = new Rectangle(dimX, dimY); } // Remove the document rotation before resizing the document. byte[] output = removeRotation(pdfOutput); PdfReader currentReader = null; try { currentReader = new PdfReader(output); } catch (IOException ex) { FormPrintException e = new PdfProcessingException("scalePdfPages - Failed to create a PDF Reader"); log.error(" scalePdfPages - Failed to create a PDF Reader "); throw e; } OutputStream baos = new ByteArrayOutputStream(); Rectangle newSize = new Rectangle(dimX, dimY); Document document = new Document(newSize, 0, 0, 0, 0); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, baos); } catch (DocumentException ex) { FormPrintException e = new PdfProcessingException("scalePdfPages - Failed to create a PDF Writer"); log.error(" scalePdfPages - Failed to create a PDF Writer "); throw e; } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page; float offsetX, offsetY; for (int i = 1; i <= currentReader.getNumberOfPages(); i++) { Rectangle currentSize = currentReader.getPageSizeWithRotation(i); if (currentReader.getPageRotation(i) != 0) { FormPrintException e = new PdfProcessingException("Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form."); log.error(" Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form. "); throw e; } //Reset the page size for each page because there may be a mix of sizes in the document. float currentWidth = currentSize.getWidth(); float currentHeight = currentSize.getHeight(); if (currentWidth > currentHeight) { newSize = landscapePageSize; } else { newSize = portraitPageSize; } document.setPageSize(newSize); document.newPage(); float factorX = newSize.getWidth() / currentSize.getWidth(); float factorY = newSize.getHeight() / currentSize.getHeight(); // Use noEnlarge if the new page size is larger than the old one // and the pages should be centered instead of enlarged. if (noEnlarge) { if (factorX > 1) { factorX = 1; } if (factorY > 1) { factorY = 1; } } if (preserveAspectRatio) { factorX = Math.min(factorX, factorY); factorY = factorX; } offsetX = (newSize.getWidth() - (currentSize.getWidth() * factorX)) / 2f; offsetY = (newSize.getHeight() - (currentSize.getHeight() * factorY)) / 2f; page = writer.getImportedPage(currentReader, i); cb.addTemplate(page, factorX, 0, 0, factorY, offsetX, offsetY); } document.close(); return ((ByteArrayOutputStream) baos).toByteArray(); }
From source file:org.jaffa.modules.printing.services.PdfHelper.java
License:Open Source License
/** * Remove the rotation from the pdfOutput document pages. *//* w w w .ja v a 2s .com*/ private static byte[] removeRotation(byte[] pdfOutput) throws FormPrintException { PdfReader currentReader = null; try { currentReader = new PdfReader(pdfOutput); } catch (IOException ex) { FormPrintException e = new PdfProcessingException( "Remove PDF Page Rotation - Failed to create a PDF Reader"); log.error(" Remove PDF Page Rotation - Failed to create a PDF Reader "); throw e; } boolean needed = false; for (int i = 1; i <= currentReader.getNumberOfPages(); i++) { if (currentReader.getPageRotation(i) != 0) { needed = true; } } if (!needed) { return pdfOutput; } OutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, baos); } catch (DocumentException ex) { FormPrintException e = new PdfProcessingException( "Remove PDF Page Rotation - Failed to create a PDF Writer"); log.error(" Remove PDF Page Rotation - Failed to create a PDF Writer "); throw e; } PdfContentByte cb = null; PdfImportedPage page; for (int i = 1; i <= currentReader.getNumberOfPages(); i++) { Rectangle currentSize = currentReader.getPageSizeWithRotation(i); currentSize = new Rectangle(currentSize.getWidth(), currentSize.getHeight()); // strip rotation document.setPageSize(currentSize); if (cb == null) { document.open(); cb = writer.getDirectContent(); } else { document.newPage(); } int rotation = currentReader.getPageRotation(i); page = writer.getImportedPage(currentReader, i); float a, b, c, d, e, f; if (rotation == 0) { a = 1; b = 0; c = 0; d = 1; e = 0; f = 0; } else if (rotation == 90) { a = 0; b = -1; c = 1; d = 0; e = 0; f = currentSize.getHeight(); } else if (rotation == 180) { a = -1; b = 0; c = 0; d = -1; e = currentSize.getWidth(); f = currentSize.getHeight(); } else if (rotation == 270) { a = 0; b = 1; c = -1; d = 0; e = currentSize.getWidth(); f = 0; } else { FormPrintException ex = new PdfProcessingException( "Remove PDF Page Rotation - Unparsable rotation value: " + rotation); log.error(" Remove PDF Page Rotation - Unparsable form rotation value: " + rotation); throw ex; } cb.addTemplate(page, a, b, c, d, e, f); } document.close(); return ((ByteArrayOutputStream) baos).toByteArray(); }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
/** uses itext to save out form data with any changes user has made */ public void saveFormsData(String file) { try {// w ww . jav a 2s .com org.jpedal.objects.acroforms.AcroRenderer formRenderer = dPDF.getCurrentFormRenderer(); if (formRenderer == null) return; PdfReader reader = new PdfReader(selectedFile); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(file)); AcroFields form = stamp.getAcroFields(); List names = formRenderer.getComponentNameList(); /** * work through all components writing out values */ for (int i = 0; i < names.size(); i++) { String name = (String) names.get(i); Component[] comps = formRenderer.getComponentsByName(name); int type = form.getFieldType(name); String value = ""; switch (type) { case AcroFields.FIELD_TYPE_CHECKBOX: if (comps.length == 1) { JCheckBox cb = (JCheckBox) comps[0]; value = cb.getName(); if (value != null) { int ptr = value.indexOf("-("); if (ptr != -1) { value = value.substring(ptr + 2, value.length() - 1); } } if (value.equals("")) value = "On"; if (cb.isSelected()) form.setField(name, value); else form.setField(name, "Off"); } else { for (int j = 0; j < comps.length; j++) { JCheckBox cb = (JCheckBox) comps[j]; if (cb.isSelected()) { value = cb.getName(); if (value != null) { int ptr = value.indexOf("-("); if (ptr != -1) { value = value.substring(ptr + 2, value.length() - 1); // name is wrong it should be the piece of field data that needs changing. //TODO itext form.setField(name, value); } } break; } } } break; case AcroFields.FIELD_TYPE_COMBO: JComboBox combobox = (JComboBox) comps[0]; value = (String) combobox.getSelectedItem(); /** * allow for user adding new value to Combo to emulate * Acrobat * String currentText = (String) * combobox.getEditor().getItem(); * * if(!currentText.equals("")) value = currentText; */ if (value == null) value = ""; form.setField(name, value); break; case AcroFields.FIELD_TYPE_LIST: JList list = (JList) comps[0]; value = (String) list.getSelectedValue(); if (value == null) value = ""; form.setField(name, value); break; case AcroFields.FIELD_TYPE_NONE: break; case AcroFields.FIELD_TYPE_PUSHBUTTON: break; case AcroFields.FIELD_TYPE_RADIOBUTTON: for (int j = 0; j < comps.length; j++) { JRadioButton radioButton = (JRadioButton) comps[j]; if (radioButton.isSelected()) { value = radioButton.getName(); if (value != null) { int ptr = value.indexOf("-("); if (ptr != -1) { value = value.substring(ptr + 2, value.length() - 1); form.setField(name, value); } } break; } } break; case AcroFields.FIELD_TYPE_SIGNATURE: break; case AcroFields.FIELD_TYPE_TEXT: JTextComponent tc = (JTextComponent) comps[0]; value = tc.getText(); form.setField(name, value); // ArrayList objArrayList = form.getFieldItem(name).widgets; // PdfDictionary dic = (PdfDictionary)objArrayList.get(0); // PdfDictionary action // =(PdfDictionary)PdfReader.getPdfObject(dic.get(PdfName.MK)); // // if (action == null) { // PdfDictionary d = new PdfDictionary(PdfName.MK); // dic.put(PdfName.MK, d); // // Color color = tc.getBackground(); // PdfArray f = new PdfArray(new int[] { color.getRed(), // color.getGreen(), color.getBlue() }); // d.put(PdfName.BG, f); // } // moderatly useful debug code // Item dd = form.getFieldItem(name); // // ArrayList objArrayList = dd.widgets; // Iterator iter1 = objArrayList.iterator(),iter2; // String strName; // PdfDictionary objPdfDict = null; // PdfName objName = null; // PdfObject objObject = null; // while(iter1.hasNext()) // { // objPdfDict = (PdfDictionary)iter1.next(); // System.out.println("PdfDictionary Object: " + // objPdfDict.toString()); // Set objSet = objPdfDict.getKeys(); // for(iter2 = objSet.iterator(); iter2.hasNext();) // { // objName = (PdfName)iter2.next(); // objObject = objPdfDict.get(objName); // if(objName.toString().indexOf("MK")!=-1) // System.out.println("here"); // System.out.println("objName: " + objName.toString() + " - // objObject:" + objObject.toString() + " - Type: " + // objObject.type()); // if(objObject.isDictionary()) // { // Set objSet2 = ((PdfDictionary)objObject).getKeys(); // PdfObject objObject2; // PdfName objName2; // for(Iterator iter3 = objSet2.iterator(); // iter3.hasNext();) // { // objName2 = (PdfName)iter3.next(); // objObject2 = ((PdfDictionary)objObject).get(objName2); // System.out.println("objName2: " + objName2.toString() + " // -objObject2: " + objObject2.toString() + " - Type: " + // objObject2.type()); // } // } // } // } break; default: break; } } stamp.close(); } catch (ClassCastException e1) { System.out.println("Expected component does not match actual component"); } catch (Exception e1) { e1.printStackTrace(); } }
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 ww.jav a 2 s. c o m 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 nup(int pageCount, PdfPageData currentPageData, ExtractPDFPagesNup extractPage) { try {// ww w .j a va 2s . c om int[] pgsToEdit = extractPage.getPages(); if (pgsToEdit == null) return; //get user choice final String output_dir = extractPage.getRootDir() + separator + fileName + separator + "PDFs" + separator; File testDirExists = new File(output_dir); if (!testDirExists.exists()) testDirExists.mkdirs(); List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); 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; } } int rows = extractPage.getLayoutRows(); int coloumns = extractPage.getLayoutColumns(); int paperWidth = extractPage.getPaperWidth(); int paperHeight = extractPage.getPaperHeight(); Rectangle pageSize = new Rectangle(paperWidth, paperHeight); String orientation = extractPage.getPaperOrientation(); Rectangle newSize = null; if (orientation.equals(Messages.getMessage("PdfViewerNUPOption.Auto"))) { if (coloumns > rows) newSize = new Rectangle(pageSize.height(), pageSize.width()); else newSize = new Rectangle(pageSize.width(), pageSize.height()); } else if (orientation.equals("Portrait")) { newSize = new Rectangle(pageSize.width(), pageSize.height()); } else if (orientation.equals("Landscape")) { newSize = new Rectangle(pageSize.height(), pageSize.width()); } String scale = extractPage.getScale(); float leftRightMargin = extractPage.getLeftRightMargin(); float topBottomMargin = extractPage.getTopBottomMargin(); float horizontalSpacing = extractPage.getHorizontalSpacing(); float verticalSpacing = extractPage.getVerticalSpacing(); Rectangle unitSize = null; if (scale.equals("Auto")) { float totalHorizontalSpacing = (coloumns - 1) * horizontalSpacing; int totalWidth = (int) (newSize.width() - leftRightMargin * 2 - totalHorizontalSpacing); int unitWidth = totalWidth / coloumns; float totalVerticalSpacing = (rows - 1) * verticalSpacing; int totalHeight = (int) (newSize.height() - topBottomMargin * 2 - totalVerticalSpacing); int unitHeight = totalHeight / rows; unitSize = new Rectangle(unitWidth, unitHeight); } else if (scale.equals("Use Original Size")) { unitSize = null; } else if (scale.equals("Specified")) { unitSize = new Rectangle(extractPage.getScaleWidth(), extractPage.getScaleHeight()); } int order = extractPage.getPageOrdering(); int pagesPerPage = rows * coloumns; int repeats = 1; if (extractPage.getRepeat() == REPEAT_AUTO) repeats = coloumns * rows; else if (extractPage.getRepeat() == REPEAT_SPECIFIED) repeats = extractPage.getCopies(); Document document = new Document(newSize, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileToSave)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage importedPage; float offsetX = 0, offsetY = 0, factor; int actualPage = 0, page = 0; Rectangle currentSize; boolean isProportional = extractPage.isScaleProportional(); for (int i = 1; i <= pageCount; i++) { if (pagesToEdit.contains(new Integer(i))) { for (int j = 0; j < repeats; j++) { int currentUnit = page % pagesPerPage; if (currentUnit == 0) { document.newPage(); actualPage++; } currentSize = reader.getPageSizeWithRotation(i); if (unitSize == null) unitSize = currentSize; int currentColoumn = 0, currentRow = 0; if (order == ORDER_DOWN) { currentColoumn = currentUnit / rows; currentRow = currentUnit % rows; offsetX = unitSize.width() * currentColoumn; offsetY = newSize.height() - (unitSize.height() * (currentRow + 1)); } else if (order == ORDER_ACCROS) { currentColoumn = currentUnit % coloumns; currentRow = currentUnit / coloumns; offsetX = unitSize.width() * currentColoumn; offsetY = newSize.height() - (unitSize.height() * ((currentUnit / coloumns) + 1)); } factor = Math.min(unitSize.width() / currentSize.width(), unitSize.height() / currentSize.height()); float widthFactor = factor, heightFactor = factor; if (!isProportional) { widthFactor = unitSize.width() / currentSize.width(); heightFactor = unitSize.height() / currentSize.height(); } else { offsetX += ((unitSize.width() - (currentSize.width() * factor)) / 2f); offsetY += ((unitSize.height() - (currentSize.height() * factor)) / 2f); } offsetX += (horizontalSpacing * currentColoumn) + leftRightMargin; offsetY -= ((verticalSpacing * currentRow) + topBottomMargin); importedPage = writer.getImportedPage(reader, i); double rotation = currentSize.getRotation() * Math.PI / 180; /** * see * http://itextdocs.lowagie.com/tutorial/directcontent/coordinates/index.html * for information about transformation matrices, and the coordinate system */ int mediaBoxX = -currentPageData.getMediaBoxX(i); int mediaBoxY = -currentPageData.getMediaBoxY(i); float a, b, c, d, e, f; switch (currentSize.getRotation()) { case 0: a = widthFactor; b = 0; c = 0; d = heightFactor; e = offsetX + (mediaBoxX * widthFactor); f = offsetY + (mediaBoxY * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; case 90: a = 0; b = (float) (Math.sin(rotation) * -heightFactor); c = (float) (Math.sin(rotation) * widthFactor); d = 0; e = offsetX + (mediaBoxY * widthFactor); f = ((currentSize.height() * heightFactor) + offsetY) - (mediaBoxX * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; case 180: a = (float) (Math.cos(rotation) * widthFactor); b = 0; c = 0; d = (float) (Math.cos(rotation) * heightFactor); e = (offsetX + (currentSize.width() * widthFactor)) - (mediaBoxX * widthFactor); f = ((currentSize.height() * heightFactor) + offsetY) - (mediaBoxY * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; case 270: a = 0; b = (float) (Math.sin(rotation) * -heightFactor); c = (float) (Math.sin(rotation) * widthFactor); d = 0; e = (offsetX + (currentSize.width() * widthFactor)) - (mediaBoxY * widthFactor); f = offsetY + (mediaBoxX * heightFactor); cb.addTemplate(importedPage, a, b, c, d, e, f); break; } page++; } } } document.close(); currentGUI.showMessageDialog( Messages.getMessage("PdfViewerMessage.PagesSavedAsPdfTo") + " " + output_dir); } catch (Exception e) { e.printStackTrace(); } }