List of usage examples for com.lowagie.text.pdf PdfReader getNumberOfPages
public int getNumberOfPages()
From source file:com.ikon.util.PDFUtils.java
License:Open Source License
public static void stampText(InputStream input, String text, int layer, float opacity, int size, Color color, int rotation, int align, String exprX, String exprY, OutputStream output) throws FileNotFoundException, DocumentException, EvalError, IOException { log.debug("stampText({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})", new Object[] { input, text, Integer.valueOf(layer), Float.valueOf(opacity), Integer.valueOf(size), color, Integer.valueOf(rotation), Integer.valueOf(align), exprX, exprY, output }); BaseFont bf = getBaseFont();/*from ww w .j av a 2s.com*/ PdfReader reader = new PdfReader(input); PdfStamper stamper = new PdfStamper(reader, output); PdfGState gs = new PdfGState(); gs.setFillOpacity(opacity); gs.setStrokeOpacity(opacity); int numPages = reader.getNumberOfPages(); int count = 0; while (count++ < numPages) { int pageCenter = (int) reader.getPageSizeWithRotation(count).getWidth() / 2; int pageMiddle = (int) reader.getPageSizeWithRotation(count).getHeight() / 2; Interpreter i = new Interpreter(); i.set("PAGE_WIDTH", (int) reader.getPageSizeWithRotation(count).getWidth()); i.set("PAGE_HEIGHT", (int) reader.getPageSizeWithRotation(count).getHeight()); i.set("PAGE_CENTER", pageCenter); i.set("PAGE_MIDDLE", pageMiddle); Integer evalX = (Integer) i.eval(exprX); Integer evalY = (Integer) i.eval(exprY); if (evalX == null) evalX = Integer.valueOf(pageCenter); if (evalY == null) { evalY = Integer.valueOf(pageMiddle); } log.debug("evalX: {}", evalX); log.debug("evalY: {}", evalY); PdfContentByte cb = null; if (layer == LAYER_UNDER_CONTENT) cb = stamper.getUnderContent(count); else if (layer == LAYER_OVER_CONTENT) cb = stamper.getOverContent(count); else { throw new IllegalArgumentException(); } cb.saveState(); cb.setColorFill(color); cb.setGState(gs); cb.beginText(); cb.setFontAndSize(bf, size); cb.showTextAligned(align, text, evalX.intValue(), evalY.intValue(), rotation); cb.endText(); cb.restoreState(); } stamper.close(); reader.close(); }
From source file:com.jk.framework.pdf.PDFMergeUtil.java
License:Apache License
/** * Concat PD fs./*from w ww. j a va2 s. c o m*/ * * @param pdfs * the pdfs * @param outputStream * the output stream * @param paginate * the paginate * @throws PdfException * the pdf exception */ // //////////////////////////////////////////////////////////////// public static void concatPDFs(final List<InputStream> pdfs, final OutputStream outputStream, final boolean paginate) throws PdfException { final Document document = new Document(); try { final List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; final Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { final InputStream pdf = iteratorPDFs.next(); final PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); // BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, // BaseFont.CP1252, BaseFont.NOT_EMBEDDED); final PdfContentByte cb = writer.getDirectContent(); // Holds the // PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; final Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { final 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 (final Exception e) { throw new PdfException(e); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (final IOException ioe) { ioe.printStackTrace(); } } }
From source file:com.moss.pdf.template.core.Renderer.java
License:Open Source License
public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception { PdfReader reader = new PdfReader(in); Document document = new Document(reader.getPageSizeWithRotation(1)); PdfWriter writer = PdfWriter.getInstance(document, out); document.open();/*from w w w.j ava 2 s .c o m*/ for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte cb = writer.getDirectContent(); PdfImportedPage customPage = writer.getImportedPage(reader, i); /* * add the page to our new document, turning this page to its * original rotation */ int pageRotation = reader.getPageRotation(i); if (pageRotation > 0) { System.out.println("page rotation found: " + pageRotation); double angle = -((2 * Math.PI) * pageRotation / 360); // double angle = -(Math.PI / 2); cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle), (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x document.top() + document.topMargin() // y ); } else { cb.addTemplate(customPage, 0f, 0f); } Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>(); for (PropertyMapping field : fields) { if (field.getPageNumber() != i) { continue; } /* * Only builtin fonts are supported at the moment */ BaseFont font; int fontSize; int alignment; String text; float x, y; float rotation; { font = fonts.get(field.getFontName()); if (font == null) { FontName e = field.getFontName(); String name = null; if (FontName.COURIER == e) { name = BaseFont.COURIER; } else if (FontName.COURIER_BOLD == e) { name = BaseFont.COURIER_BOLD; } else if (FontName.COURIER_BOLD_OBLIQUE == e) { name = BaseFont.COURIER_BOLDOBLIQUE; } else if (FontName.COURIER_OBLIQUE == e) { name = BaseFont.COURIER_OBLIQUE; } else if (FontName.HELVETICA == e) { name = BaseFont.HELVETICA; } else if (FontName.HELVETICA_BOLD == e) { name = BaseFont.HELVETICA_BOLD; } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) { name = BaseFont.HELVETICA_BOLDOBLIQUE; } else if (FontName.HELVETICA_OBLIQUE == e) { name = BaseFont.HELVETICA_OBLIQUE; } else if (FontName.TIMES_BOLD == e) { name = BaseFont.TIMES_BOLD; } else if (FontName.TIMES_BOLD_ITALIC == e) { name = BaseFont.TIMES_BOLDITALIC; } else if (FontName.TIMES_ITALIC == e) { name = BaseFont.TIMES_ITALIC; } else if (FontName.TIMES_ROMAN == e) { name = BaseFont.TIMES_ROMAN; } if (name == null) { throw new RuntimeException("Unknown font type: " + e); } font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); fonts.put(field.getFontName(), font); } fontSize = field.getFontSize(); if (TextAlignment.LEFT == field.getAlignment()) { alignment = PdfContentByte.ALIGN_LEFT; } else if (TextAlignment.CENTER == field.getAlignment()) { alignment = PdfContentByte.ALIGN_CENTER; } else if (TextAlignment.RIGHT == field.getAlignment()) { alignment = PdfContentByte.ALIGN_RIGHT; } else { alignment = PdfContentByte.ALIGN_LEFT; } Object value = p.eval(field.getExpr()); if (value == null) { text = ""; } else { text = value.toString(); } x = field.getX() * POINTS_IN_A_CM; y = field.getY() * POINTS_IN_A_CM; rotation = 0; } cb.beginText(); cb.setFontAndSize(font, fontSize); cb.showTextAligned(alignment, text, x, y, rotation); cb.endText(); } document.newPage(); } reader.close(); document.close(); }
From source file:com.openkm.util.PDFUtils.java
License:Open Source License
/** * Merge several PDFs into a new one//from ww w . j a v a 2 s . co m */ public static void merge(List<InputStream> inputs, OutputStream output) throws IOException, DocumentException { Document document = new Document(); try { PdfSmartCopy copy = new PdfSmartCopy(document, output); document.open(); for (InputStream is : inputs) { PdfReader reader = new PdfReader(is); for (int i = 1; i <= reader.getNumberOfPages(); i++) { copy.addPage(copy.getImportedPage(reader, i)); } } output.flush(); document.close(); } finally { IOUtils.closeQuietly(output); } }
From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java
License:Apache License
/** * Adds a logo to the given pdf file./* ww w . ja v a 2 s . co m*/ * @param pdfFileName * @param imageFileName * @param x position for image * @param y position for image * @throws Exception */ public void addWatermark(String pdfFileName, String imageFileName, int x, int y) throws Exception { // 1. copy File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf"); copyFile(new File(pdfFileName), tmpPDFFile); // 2. add watermark // we create a reader for a certain document PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath()); int n = reader.getNumberOfPages(); // we create a stamper that will copy the document to a new file PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName)); // adding content to each page int i = 0; PdfContentByte under; Image img = Image.getInstance(imageFileName); img.setAbsolutePosition(x, y); while (i < n) { i++; // watermark under the existing page under = stamp.getUnderContent(i); under.addImage(img); } // closing PdfStamper will generate the new PDF file stamp.close(); }
From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java
License:Apache License
public void addTemplate(String pdfFileName, String templatePDFFileName) throws Exception { // see example on http://itextdocs.lowagie.com/examples/com/lowagie/examples/general/copystamp/AddWatermarkPageNumbers.java // 1. copy/* w w w. j a v a2 s .co m*/ File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf"); copyFile(new File(pdfFileName), tmpPDFFile); // 2. add template on all pages // we create a reader for a certain document PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath()); // we create a stamper that will copy the document to a new file PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(pdfFileName)); // adding content to each page int n = reader.getNumberOfPages(); int i = 0; // a reader for the template document PdfReader reader2 = new PdfReader(templatePDFFileName); PdfContentByte under; while (i < n) { i++; // template under the existing page under = stamp.getUnderContent(i); //under.addTemplate(stamp.getImportedPage(reader2, 1), 1, 0, 0, 1, 0, 0); under.addTemplate(stamp.getImportedPage(reader2, 1), -10, -50); } // closing PdfStamper will generate the new PDF file stamp.close(); }
From source file:com.sapienter.jbilling.server.invoice.PaperInvoiceBatchBL.java
License:Open Source License
/** * Takes a list of invoices and replaces the individual PDF files for one * single PDF in the destination directory. * @param destination/*w w w . ja v a 2 s . c om*/ * @param prefix * @param entityId * @param invoices * @throws PdfFormatException * @throws IOException */ public void compileInvoiceFiles(String destination, String prefix, Integer entityId, Integer[] invoices) throws DocumentException, IOException { String filePrefix = Util.getSysProp("base_dir") + "invoices/" + entityId + "-"; String outFile = destination + prefix + "-batch.pdf"; int pageOffset = 0; ArrayList master = new ArrayList(); Document document = null; PdfCopy writer = null; for (int f = 0; f < invoices.length; f++) { // we create a reader for a certain document PdfReader reader = new PdfReader(filePrefix + invoices[f] + "-invoice.pdf"); reader.consolidateNamedDestinations(); // we retrieve the total number of pages int numberOfPages = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); master.addAll(bookmarks); } pageOffset += numberOfPages; if (f == 0) { // 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, new FileOutputStream(outFile)); // step 3: we open the document document.open(); } // step 4: we add content PdfImportedPage page; for (int i = 0; i < numberOfPages;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); //release and delete writer.freeReader(reader); reader.close(); File file = new File(filePrefix + invoices[f] + "-invoice.pdf"); file.delete(); } if (!master.isEmpty()) writer.setOutlines(master); // step 5: we close the document if (document != null) { document.close(); } else { LOG.warn("document == null"); } LOG.debug("PDF batch file is ready " + outFile); }
From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java
License:Open Source License
/** * Combine multiple protected PDF docs into one. * Note: this function may fail when creating large PDF files due to lack of available heap memory. To compensate, please configure the application server with more heap memory via -Xmx parameter. * * @sample//from w ww.j a v a2 s . c o m * pdf_blob_column = combineProtectedPDFDocuments(new Array(pdf_blob1,pdf_blob2,pdf_blob3), new Array(pdf_blob1_pass,pdf_blob2_pass,pdf_blob3_pass)); * * @param pdf_docs_bytearrays the array of documents to combine * @param pdf_docs_passwords an array of passwords to use */ public byte[] js_combineProtectedPDFDocuments(Object[] pdf_docs_bytearrays, Object[] pdf_docs_passwords) { if (pdf_docs_bytearrays == null || pdf_docs_bytearrays.length == 0) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int pageOffset = 0; List master = new ArrayList(); Document document = null; PdfCopy writer = null; for (int f = 0; f < pdf_docs_bytearrays.length; f++) { if (!(pdf_docs_bytearrays[f] instanceof byte[])) continue; byte[] pdf_file = (byte[]) pdf_docs_bytearrays[f]; // we create a reader for a certain document byte[] password = null; if (pdf_docs_passwords != null && pdf_docs_passwords.length > f && pdf_docs_passwords[f] != null) { if (pdf_docs_passwords[f] instanceof String) password = pdf_docs_passwords[f].toString().getBytes(); } PdfReader reader = new PdfReader(pdf_file, password); 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 (writer == null) { // 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, 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); } PRAcroForm form = reader.getAcroForm(); if (form != null) writer.copyAcroForm(reader); } if (writer != null && document != null) { if (master.size() > 0) writer.setOutlines(master); // step 5: we close the document document.close(); } return baos.toByteArray(); } catch (Throwable e) { Debug.error(e); throw new RuntimeException("Error combinding pdf documents: " + e.getMessage(), e); //$NON-NLS-1$ } }
From source file:com.silverpeas.importExport.control.ImportExport.java
License:Open Source License
/** * @param userDetail/*w w w. ja v a 2 s . c o m*/ * @param itemsToExport * @return * @throws ImportExportException */ public ExportPDFReport processExportPDF(UserDetail userDetail, List<WAAttributeValuePair> itemsToExport, NodePK rootPK) throws ImportExportException { ExportPDFReport report = new ExportPDFReport(); report.setDateDebut(new Date()); PublicationsTypeManager pubTypeManager = new PublicationsTypeManager(); String fileExportName = generateExportDirName(userDetail, "fusion"); String tempDir = FileRepositoryManager.getTemporaryPath(); File fileExportDir = new File(tempDir + fileExportName); if (!fileExportDir.exists()) { try { FileFolderManager.createFolder(fileExportDir); } catch (UtilException ex) { throw new ImportExportException("ImportExport", "importExport.EX_CANT_CREATE_FOLDER", ex); } } File pdfFileName = new File(tempDir + fileExportName + ".pdf"); try { // cration des rpertoires avec le nom des thmes et des publications List<AttachmentDetail> pdfList = pubTypeManager.processPDFExport(report, userDetail, itemsToExport, fileExportDir.getPath(), true, rootPK); try { int pageOffset = 0; List master = new ArrayList(); Document document = null; PdfCopy writer = null; if (!pdfList.isEmpty()) { boolean firstPage = true; for (AttachmentDetail attDetail : pdfList) { PdfReader reader = null; try { reader = new PdfReader( fileExportDir.getPath() + File.separatorChar + attDetail.getLogicalName()); } catch (IOException ioe) { // Attached file is not physically present on disk, ignore it and log event SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF", "CANT_FIND_PDF_FILE", "PDF file '" + attDetail.getLogicalName() + "' is not present on disk", ioe); } if (reader != null) { reader.consolidateNamedDestinations(); int nbPages = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += nbPages; if (firstPage) { document = new Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, new FileOutputStream(pdfFileName)); document.open(); firstPage = false; } for (int i = 1; i <= nbPages; i++) { try { PdfImportedPage page = writer.getImportedPage(reader, i); writer.addPage(page); } catch (Exception e) { // Can't import PDF file, ignore it and log event SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF", "CANT_MERGE_PDF_FILE", "PDF file is " + attDetail.getLogicalName(), e); } } PRAcroForm form = reader.getAcroForm(); if (form != null) { writer.copyAcroForm(reader); } } } if (!master.isEmpty()) { writer.setOutlines(master); } writer.flush(); document.close(); } else { return null; } } catch (BadPdfFormatException e) { // Erreur lors de la copie throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } catch (DocumentException e) { // Impossible de copier le document throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } } catch (IOException e) { // Pb avec le rpertoire de destination throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e); } report.setPdfFileName(pdfFileName.getName()); report.setPdfFileSize(pdfFileName.length()); report.setPdfFilePath(FileServerUtils.getUrlToTempDir(pdfFileName.getName())); report.setDateFin(new Date()); return report; }
From source file:com.square.adherent.noyau.service.implementations.RelevePrestationServiceImpl.java
License:Open Source License
@Override public FichierDto getRelevePrestationByteArray(Long idRelevePrestation, Long idPersonne, boolean duplicata) { logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_CONVERSION_RELEVE_PRESTATION, new String[] { String.valueOf(idRelevePrestation) })); final CritereSelectionRelevePrestationDto critereSelectionRelevePrestationDto = new CritereSelectionRelevePrestationDto(); critereSelectionRelevePrestationDto.setRelevePrestationId(idRelevePrestation); if (idPersonne != null) { critereSelectionRelevePrestationDto.setIdPersonne(idPersonne); }// ww w.j av a 2s .c o m final List<RelevePrestation> lstReleves = relevePrestationDao .getListeReleveParCriteres(critereSelectionRelevePrestationDto, null); if (lstReleves.size() == 1) { final RelevePrestation releve = lstReleves.get(0); final String error = messageSourceUtil.get(MessageKeyUtil.ERROR_RECUPERATION_FICHIER); FichierDto fichier; final String cheminFichier = serveurEmcRepReleve + File.separator + releve.getNomFichier(); try { fichier = new FichierDto(); fichier.setNomFichier(releve.getNomFichierCommercial()); if (duplicata) { // On appose la mention "DUPLICATA" sur toutes les pages du relev. try { final PdfReader reader = new PdfReader(cheminFichier); final int nombrePages = reader.getNumberOfPages(); final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.WINANSI, BaseFont.EMBEDDED); final PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FICHIER_DUPLICATA_TEMP)); final int taillePolice = 56; final int positionX = ((int) PageSize.A4.getWidth()) / 2; final int positionY = ((int) PageSize.A4.getHeight()) / 2; final int rotation = 30; for (int i = 1; i <= nombrePages; i++) { final PdfContentByte over = stamp.getOverContent(i); over.beginText(); over.setColorFill(Color.GRAY); final PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(NIVEAU_TRANSPARENCE); over.setGState(gs1); over.setFontAndSize(bf, taillePolice); over.showTextAligned(PdfContentByte.ALIGN_CENTER, "DUPLICATA", positionX, positionY, rotation); over.endText(); } stamp.close(); reader.close(); fichier.setContenu(IOUtils.toByteArray(new FileInputStream(FICHIER_DUPLICATA_TEMP))); final File file = new File(FICHIER_DUPLICATA_TEMP); file.delete(); } catch (DocumentException e) { throw new TechnicalException( messageSourceUtil.get(MessageKeyUtil.ERROR_IMPOSSIBLE_AJOUTER_MENTION_DUPLICATA, new String[] { releve.getNomFichier() })); } } else { fichier.setContenu(IOUtils.toByteArray(new FileInputStream(cheminFichier))); } fichier.setTypeMime(Magic.getMagicMatch(fichier.getContenu()).getMimeType()); } catch (FileNotFoundException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (IOException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicParseException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicMatchNotFoundException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } return fichier; } else { throw new TechnicalException( messageSourceUtil.get(MessageKeyUtil.ERROR_ABSCENCE_RELEVE_PRESTATION_PERSONNE)); } }