List of usage examples for com.itextpdf.text.pdf PdfReader close
public void close()
From source file:controller.DownloadCVServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request//from w ww. j av a 2 s . c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //protect servlet HttpSession session = request.getSession(); Admin loggedInAdmin = (Admin) session.getAttribute("admin"); //check if admin is logged in if (loggedInAdmin == null) { response.sendRedirect("login.jsp"); return; } String[] appIDs = request.getParameterValues("download"); ServletOutputStream sOut = response.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); //prepare fonts Font font = FontFactory.getFont("Arial", 10); for (String appIDStr : appIDs) { int appID = Integer.parseInt(appIDStr); Application application = ApplicationDAO.retrieveByAppID(appID); Job job = JobDAO.retrieveJobById(application.getJobID()); ZipEntry entry = new ZipEntry(application.getFullname() + "_CV.pdf"); zos.putNextEntry(entry); String path = System.getenv("OPENSHIFT_DATA_DIR"); if (path == null) { path = getServletContext().getRealPath("/templates/Personal_Particulars_Form.pdf"); } else { path += "Personal_Particulars_Form.pdf"; } try { //Prepare PdfStamper PdfReader reader = new PdfReader(path); PdfStamper stamper = new PdfStamper(reader, zos); stamper.setRotateContents(false); stamper.getWriter().setCloseStream(false); //Get first page PdfContentByte canvas = stamper.getOverContent(1); //Application ID ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getAppID() + "", font), 110, 555, 0); //Date Applied ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getDateApplied(), font), 110, 526, 0); //Position Applied ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(job.getPostingTitle(), font), 36, 442, 0); //Job ID ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getJobID() + "", font), 405, 442, 0); //Name ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getFullname(), font), 36, 350, 0); //Street ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getBlkStreetUnit(), font), 36, 305, 0); //Postal Code ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getPostalCode(), font), 377, 305, 0); //Nationality ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNricType(), font), 36, 260, 0); //NRIC ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNric(), font), 289, 260, 0); //DOB ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getDob(), font), 36, 215, 0); //Gender ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getGender(), font), 379, 215, 0); //Contact Number ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getContactNo(), font), 36, 170, 0); //Email Address ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getEmailAddress(), font), 36, 125, 0); //Declaration ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("X", font), 50, 80, 0); //Generated on DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Singapore")); Date date = new Date(); String today = dateFormat.format(date); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(today, font), 437, 15, 0); stamper.close(); reader.close(); } catch (DocumentException e) { e.printStackTrace(); } } zos.close(); response.setContentType("application/zip"); response.addHeader("Content-Disposition", "attachment; filename=CVs.zip"); sOut.write(baos.toByteArray()); sOut.close(); }
From source file:cz.hobrasoft.pdfmu.operation.OperationInspect.java
License:Open Source License
public Inspect execute(File file) throws OperationException, IOException { assert file != null; Inspect result;//from w w w . j a v a 2s . c om try (InputStream is = new FileInputStream(file)) { PdfReader pdfReader = new PdfReader(is); try { result = execute(pdfReader); } finally { pdfReader.close(); } } return result; }
From source file:cz.muni.pdfjbim.PdfImageExtractor.java
License:Apache License
/** * Extracts JBIG2Images from Input stream even if they are stored together with global dictionary in separate PDF object * doesn't work yet, its in development stage * @param is/*from www . j a v a 2 s . co m*/ * @throws PdfRecompressionException * @deprecated */ public void extractJbig2Images(InputStream is) throws PdfRecompressionException { if (is == null) { throw new IllegalArgumentException("InputStream not given"); } PdfReader pdfReader = null; try { pdfReader = new PdfReader(is); for (int i = 0; i <= pdfReader.getNumberOfPages(); i++) { PdfDictionary d = pdfReader.getPageN(i); PdfIndirectReference ir = d.getAsIndirectObject(PdfName.CONTENTS); PdfObject o = pdfReader.getPdfObject(ir.getNumber()); PdfStream stream = (PdfStream) o; PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE); if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) { byte[] img = PdfReader.getStreamBytesRaw((PRStream) stream); OutputStream out = new FileOutputStream( new File("pdfRecompressor", String.format("%1$05d", i) + ".jpg")); out.write(img); out.flush(); out.close(); } } } catch (IOException ex) { log.error("IOException caught while trying to extract jbig2 images from PDF", ex); throw new PdfRecompressionException("IOException caught while trying to extract jbig2 images from PDF", ex); } finally { if (pdfReader != null) { pdfReader.close(); } } }
From source file:de.drippinger.cytricHelper.CytricHelper.java
License:Open Source License
public void manipulatePdf(String sourceFile, String expenseID) throws IOException, DocumentException { PdfReader reader = new PdfReader(sourceFile); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(getOutputName(sourceFile))); PdfContentByte over = stamper.getOverContent(1); Phrase p = new Phrase(String.format("Cytric ID: %s", expenseID)); ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 500, reader.getPageSize(1).getHeight() - 30, 0); over.saveState();//from w w w . j a v a2 s. com stamper.close(); reader.close(); }
From source file:de.earthdawn.ECEPdfExporter.java
License:Open Source License
public void exportSpellcards(EDCHARACTER edCharakter, File outFile, int version) throws DocumentException, IOException { CharacterContainer character = new CharacterContainer(edCharakter); File template = null;/*from w w w . ja v a2 s.c om*/ int maxSpellPerPage = 1; switch (version) { case 0: default: template = new File("./templates/spellcards_portrait_2x2.pdf"); maxSpellPerPage = 4; break; case 1: template = new File("./templates/spellcards_landscape_2x2.pdf"); maxSpellPerPage = 4; break; } String filename = outFile.getCanonicalPath(); String filenameBegin = ""; String filenameEnd = ""; int dotPosition = filename.lastIndexOf('.'); if (dotPosition >= 0) { filenameBegin = filename.substring(0, dotPosition); filenameEnd = filename.substring(dotPosition); } else { filenameBegin = filename; } int counterFile = 0; int counterSpells = maxSpellPerPage; PdfStamper stamper = null; PdfReader reader = null; HashMap<String, SpelldescriptionType> spelldescriptions = ApplicationProperties.create() .getSpellDescriptions(); List<List<SPELLType>> spellslist = new ArrayList<List<SPELLType>>(); List<String> disciplineNames = new ArrayList<String>(); spellslist.add(character.getOpenSpellList()); disciplineNames.add(""); for (DISCIPLINEType discipline : character.getDisciplines()) { spellslist.add(discipline.getSPELL()); disciplineNames.add(discipline.getName()); } int spelllistnr = 0; for (List<SPELLType> spells : spellslist) { Collections.sort(spells, new SpellComparator()); for (SPELLType spell : spells) { if (counterSpells < maxSpellPerPage) { counterSpells++; } else { if (stamper != null) stamper.close(); if (reader != null) reader.close(); reader = new PdfReader(new FileInputStream(template)); stamper = new PdfStamper(reader, new FileOutputStream( new File(filenameBegin + String.format("%02d", counterFile) + filenameEnd))); acroFields = stamper.getAcroFields(); counterSpells = 1; counterFile++; } acroFields.setField("Discipline" + counterSpells, disciplineNames.get(spelllistnr)); acroFields.setField("Spell Name" + counterSpells, spell.getName()); acroFields.setField("Spell Circle" + counterSpells, String.valueOf(spell.getCircle())); acroFields.setField("Spellcasting" + counterSpells, spell.getCastingdifficulty()); acroFields.setField("Threads" + counterSpells, spell.getThreads()); acroFields.setField("Weaving" + counterSpells, spell.getWeavingdifficulty()); acroFields.setField("Reattuning" + counterSpells, String.valueOf(spell.getReattuningdifficulty())); acroFields.setField("Range" + counterSpells, spell.getRange()); acroFields.setField("Duration" + counterSpells, spell.getDuration()); acroFields.setField("Effect" + counterSpells, spell.getEffect()); acroFields.setField("Page reference" + counterSpells, String.valueOf(spell.getBookref())); acroFields.setField("Air" + counterSpells, "No"); acroFields.setField("Earth" + counterSpells, "No"); acroFields.setField("Fear" + counterSpells, "No"); acroFields.setField("Fire" + counterSpells, "No"); acroFields.setField("Illusion" + counterSpells, "No"); acroFields.setField("Illusion N" + counterSpells, "Yes"); acroFields.setField("Water" + counterSpells, "No"); acroFields.setField("Wood" + counterSpells, "No"); switch (spell.getElement()) { case AIR: acroFields.setField("Air" + counterSpells, "Yes"); break; case EARTH: acroFields.setField("Earth" + counterSpells, "Yes"); break; case FEAR: acroFields.setField("Fear" + counterSpells, "Yes"); break; case FIRE: acroFields.setField("Fire" + counterSpells, "Yes"); break; case ILLUSION: acroFields.setField("Illusion" + counterSpells, "Yes"); acroFields.setField("Illusion N" + counterSpells, "No"); break; case WATER: acroFields.setField("Water" + counterSpells, "Yes"); break; case WOOD: acroFields.setField("Wood" + counterSpells, "Yes"); break; case UNDEFINED: break; } SpelldescriptionType spelldescription = spelldescriptions.get(spell.getName()); if ((spelldescription == null) || (spelldescription.getValue() == null)) acroFields.setField("Spell description" + counterSpells, ""); else acroFields.setField("Spell description" + counterSpells, spelldescription.getValue()); } spelllistnr++; } stamper.close(); }
From source file:de.extra.xtt.util.pdf.PdfCreatorImpl.java
License:Apache License
/** * Erzeugt das Inhaltsverzeichnis aus den bereits vorhandenen Elementen in * der Liste <code>listEntries</code>. * /*from w w w. ja v a 2s . c o m*/ * @param docPdf * Zieldokument, falls Inhaltsverzeichnis nicht temporr erzeugt * wird * @param temp * Gibt an, ob das Inhaltsverzeichnis temporr in einer neuen * Datei/Dokument erzeugt werden soll * @return Anzahl der Seiten * @throws DocumentException * @throws IOException */ private int erzeugeInhaltsverzeichnis(Document docPdf, boolean temp) throws DocumentException, IOException { int anzPages = 0; Document docInhalt = docPdf; String filePathTempInhaltString = ""; if (temp) { // temp. Dateinamen bestimmen File fileDokuFile = new File(dateiname); filePathTempInhaltString = fileDokuFile.getParent() + "/tmp_inhalt.pdf"; // Neues Dokument erzeugen docInhalt = initPdfWriterAndDocument(filePathTempInhaltString, false); } // berschrift Chapter currChapter = new Chapter(getParagraphChapter("Inhaltsverzeichnis"), 0); // 0, damit keine Nummerierung currChapter.setNumberDepth(0); docInhalt.add(currChapter); // eine Zeile Abstand docInhalt.add(getEmptyLineTextHalf()); for (ContPdfEntry currEntry : listEntries) { // Eintrag erzeugen inkl. Abstand String strEintrag = currEntry.getBezeichnung() + " "; Chunk chunkBezeichnung; Chunk chunkSeitenzahlChunk; if (currEntry.getParentEntry() == null) { // 1. Ebene => fett, Abstand davor einfgen docInhalt.add(getEmptyLineTextHalf()); chunkBezeichnung = getChunkTextBold(strEintrag); chunkSeitenzahlChunk = getChunkTextBold("" + currEntry.getPageNumber()); } else { // 2. Ebene chunkBezeichnung = getChunkText(strEintrag); chunkSeitenzahlChunk = getChunkText("" + currEntry.getPageNumber()); } // Referenz setzen chunkBezeichnung.setLocalGoto(currEntry.getDestination()); chunkSeitenzahlChunk.setLocalGoto(currEntry.getDestination()); // Abstandzeichen generieren, Breite auffllen float widthAbstand = docInhalt.getPageSize().getWidth() * 0.81f; ; while (chunkBezeichnung.getWidthPoint() <= widthAbstand) { chunkBezeichnung.append("."); } // Tabelle erzeugen und formatieren PdfPTable currTable = new PdfPTable(2); currTable.setWidthPercentage(100f); currTable.setWidths(new int[] { 96, 4 }); // Inhalte einfgen // Zelle Bezeichnung PdfPCell currCellBezeichnung = new PdfPCell(new Phrase(chunkBezeichnung)); currCellBezeichnung.setBorder(0); currCellBezeichnung.setHorizontalAlignment(Element.ALIGN_JUSTIFIED_ALL); // Zelle Seitennummer PdfPCell currCellPageNumberCell = new PdfPCell(new Phrase(chunkSeitenzahlChunk)); currCellPageNumberCell.setBorder(0); currCellPageNumberCell.setHorizontalAlignment(Element.ALIGN_RIGHT); // Zellen zur Tabelle hinzufgen currTable.addCell(currCellBezeichnung); currTable.addCell(currCellPageNumberCell); docInhalt.add(currTable); } if (temp) { // Dokument schlieen docInhalt.close(); // Anzahl der Seitenzahlen bestimmen PdfReader reader = new PdfReader(filePathTempInhaltString); anzPages = reader.getNumberOfPages(); reader.close(); // temp. Datei lschen File currFileInhaltFile = new File(filePathTempInhaltString); currFileInhaltFile.delete(); } return anzPages; }
From source file:de.mat.utils.pdftools.PdfAddPageNum.java
License:Mozilla Public License
/** * <h4>FeatureDomain:</h4>/*w w w . j a v a 2s .co m*/ * PublishingTools * <h4>FeatureDescription:</h4> * read srcFile, adds pagenum and writes pages to destFile * <h4>FeatureResult:</h4> * <ul> * <li>creates destFile - output to destFile * </ul> * <h4>FeatureKeywords:</h4> * PDF Publishing * @param srcFile - source-file * @param destFile - destination-file * @param pageOffset - offset added to pagenumber * @throws Exception */ public void addPageNumber(String srcFile, String destFile, int pageOffset) throws Exception { PdfReader reader = null; PdfStamper stamper = null; try { // open files reader = new PdfReader(srcFile); stamper = new PdfStamper(reader, new FileOutputStream(destFile)); // add pagenum addPageNumber(reader, stamper, pageOffset); } catch (Exception ex) { // return Exception throw new Exception(ex); } finally { //close everything if (stamper != null) { stamper.close(); } if (reader != null) { reader.close(); } } }
From source file:de.mat.utils.pdftools.PdfExtractEmptyPages.java
License:Mozilla Public License
/** * <h4>FeatureDomain:</h4>//from w w w. j a v a2 s . c om * PublishingTools * <h4>FeatureDescription:</h4> * reads pdfSourceFile and adds pages to pdfRemovedFile if empty, or to * pdfDestinationFile if not empty * <h4>FeatureResult:</h4> * <ul> * <li>updates pdfDestinationFile - add all pages which are not empty * <li>updates pdfRemovedFile - add all empty pages * </ul> * <h4>FeatureKeywords:</h4> * PDF Publishing * @param pdfSourceFile - source pdf-file * @param pdfDestinationFile - pdf with all not empty pages * @param pdfRemovedFile - pdf with all empty pages * @throws Exception */ public static void removeBlankPdfPages(String pdfSourceFile, String pdfDestinationFile, String pdfRemovedFile) throws Exception { // create readerOrig PdfReader readerOrig = new PdfReader(pdfSourceFile); // create writerTrimmed which bases on readerOrig Document documentTrimmed = new Document(readerOrig.getPageSizeWithRotation(1)); PdfCopy writerTrimmed = new PdfCopy(documentTrimmed, new FileOutputStream(pdfDestinationFile)); documentTrimmed.open(); // create writerRemoved which bases on readerOrig Document documentRemoved = new Document(readerOrig.getPageSizeWithRotation(1)); PdfCopy writerRemoved = new PdfCopy(documentRemoved, new FileOutputStream(pdfRemovedFile)); documentRemoved.open(); // extract and copy empty pages addTrimmedPages(pdfSourceFile, readerOrig, writerTrimmed, writerRemoved, true); // close everything documentTrimmed.close(); writerTrimmed.close(); documentRemoved.close(); writerRemoved.close(); readerOrig.close(); }
From source file:de.mat.utils.pdftools.PdfMerge.java
License:Mozilla Public License
/** * <h4>FeatureDomain:</h4>/*from w w w. j av a 2 s. c o m*/ * PublishingTools * <h4>FeatureDescription:</h4> * merge pdfs from lstBookMarks to fileNew and trim empty pages if flgTrim * is set * <h4>FeatureResult:</h4> * <ul> * <li>create PDF - fileNew * <li>updates lstBookMarks - updates PAGE (firstPageNum) and * PAGES (countPage= per Bookmark * </ul> * <h4>FeatureKeywords:</h4> * PDF Publishing * @param lstBookMarks - list of Bookmark (files to merge) * @param fileNew - destination PDF filename * @param flgTrim - trim empty pages * @throws Exception */ public static void mergePdfs(List<Bookmark> lstBookMarks, String fileNew, boolean flgTrim) throws Exception { // FirstFile Map curBookMark = (Map) lstBookMarks.get(0); String curFileName = (String) curBookMark.get("SRC"); // Neues Dokument anlegen aus 1. Quelldokument anlegen PdfReader reader = new PdfReader(curFileName); Document documentNew = new Document(reader.getPageSizeWithRotation(1)); reader.close(); PdfCopy writerNew = new PdfCopy(documentNew, new FileOutputStream(fileNew)); documentNew.open(); int siteNr = 1; for (Iterator iter = lstBookMarks.iterator(); iter.hasNext();) { curBookMark = (Map) iter.next(); curFileName = (String) curBookMark.get("SRC"); if (LOGGER.isInfoEnabled()) LOGGER.info("add File:" + curFileName); // copy Page reader = new PdfReader(curFileName); int newPages = PdfExtractEmptyPages.addTrimmedPages(curFileName, reader, writerNew, (PdfCopy) null, flgTrim); reader.close(); // update BookMark curBookMark.put("PAGE", new Integer(siteNr)); curBookMark.put("PAGES", new Integer(newPages)); siteNr += newPages; } documentNew.close(); writerNew.close(); }
From source file:de.mat.utils.pdftools.PdfSort4Print.java
License:Mozilla Public License
public static void sortPdfPages(String pdfSourceFile, String pdfDestinationFile, int perPage) throws Exception { PdfImportedPage page = null;/* w w w . j ava 2 s . c o m*/ if (perPage != 2 && perPage != 4) { throw new IllegalArgumentException( "Sorry, perPage must only be " + "2 or 4. All other is not implemented yet :-("); } // ####### // # fill to odd pagecount // ####### // create reader PdfReader readerOrig = new PdfReader(pdfSourceFile); // calc data int countPage = readerOrig.getNumberOfPages(); int blaetter = new Double(Math.ceil((countPage + 0.0) / perPage / 2)).intValue(); int zielPages = (blaetter * perPage * 2) - countPage; if (LOGGER.isInfoEnabled()) LOGGER.info("CurPages: " + countPage + " Blaetter:" + blaetter + " AddPage:" + zielPages); // add sites String oddFile = pdfDestinationFile + ".filled.pdf"; PdfStamper stamper = new PdfStamper(readerOrig, new FileOutputStream(oddFile)); // add empty pages for (int i = 1; i <= zielPages; i++) { if (LOGGER.isDebugEnabled()) LOGGER.debug("addEmptyPage: " + i); stamper.insertPage(readerOrig.getNumberOfPages() + 1, readerOrig.getPageSizeWithRotation(1)); } stamper.close(); readerOrig.close(); // ######## // # read new odd document and sort pages // ######## // step 1: create new reader PdfReader readerOdd = new PdfReader(oddFile); // create writerSorted String sortedFile = pdfDestinationFile; Document documentSorted = new Document(readerOrig.getPageSizeWithRotation(1)); PdfCopy writerSorted = new PdfCopy(documentSorted, new FileOutputStream(sortedFile)); documentSorted.open(); // add pages in calced order List<Integer> lstPageNr = new ArrayList<Integer>(); int pageCount = readerOdd.getNumberOfPages(); int startseite = 1; for (int i = 1; i <= blaetter; i++) { if (perPage == 2) { startseite = ((i - 1) * perPage) + 1; if (LOGGER.isDebugEnabled()) LOGGER.debug("Blatt:" + i + " Startseite: " + startseite); // front top lstPageNr.add(new Integer(pageCount - startseite + 1)); // front bottom lstPageNr.add(new Integer(startseite)); // back top lstPageNr.add(new Integer(startseite + 1)); // back bottom lstPageNr.add(new Integer(pageCount - startseite + 1 - 1)); } else if (perPage == 4) { startseite = ((i - 1) * perPage) + 1; if (LOGGER.isDebugEnabled()) LOGGER.debug("Blatt:" + i + " Startseite: " + startseite); // front top left lstPageNr.add(new Integer(pageCount - startseite + 1)); // front top right lstPageNr.add(new Integer(startseite)); // front bottom lefts lstPageNr.add(new Integer(pageCount - startseite + 1 - 2)); // front bottom right lstPageNr.add(new Integer(startseite + 2)); // back top left lstPageNr.add(new Integer(startseite + 1)); // back top right lstPageNr.add(new Integer(pageCount - startseite + 1 - 1)); // back bottom left lstPageNr.add(new Integer(startseite + 1 + 2)); // back bottom right lstPageNr.add(new Integer(pageCount - startseite + 1 - 1 - 2)); } else { throw new IllegalArgumentException( "Sorry, perPage must " + "only be 2 or 4. All other is not implemented yet :-("); } } if (LOGGER.isInfoEnabled()) LOGGER.info("Seiten:" + lstPageNr.size()); // copy pages for (Iterator iter = lstPageNr.iterator(); iter.hasNext();) { int pageNum = ((Integer) iter.next()).intValue(); if (LOGGER.isDebugEnabled()) LOGGER.debug("addSortPage: " + pageNum); page = writerSorted.getImportedPage(readerOdd, pageNum); writerSorted.addPage(page); } // close everything documentSorted.close(); writerSorted.close(); readerOdd.close(); // delete Tmp-File File file = new File(oddFile); file.delete(); }