List of usage examples for com.itextpdf.text.pdf PdfWriter close
@Override public void close()
Document
was closed and that no other Elements
will be added. From source file:jati.GerandoArquivoCarimbado.java
public static void GerandoArquivoCarimbadoPDF(String caminhoarquivo, String BN) throws InvalidPdfException, IOException { //Copiando arquivo informado. try {/*from w w w. j a v a 2 s . c o m*/ // Adicionado parametro para nao retornar erro quando o documento for protegido. PdfReader.unethicalreading = true; PdfWriter writer = PdfWriter.getInstance(montaraAquivo(caminhoarquivo), new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf")); // ABRE O DOCUMENTO CRIADO PARA MANUSEIO montaraAquivo(caminhoarquivo).open(); //SUBSTRING RETIRA PARTE DO TEXTO ENTRE OS INDICES ESPECIFICADOS //caminhoDestino RECEBE UM NOVO CAMINHO RESULTANTE DOS INDICES DE CAMINHO.LENGTH - BN.LENGTH // QUE FORMAM UMA NOVA STRING String caminhodestino = (caminhoarquivo.substring(0, caminhoarquivo.length() - BN.length())); File destinooriginal = new File(caminhodestino + "ORIGINAL\\"); if (!destinooriginal.exists()) { destinooriginal.mkdir(); } caminhodestino = (caminhodestino + "ORIGINAL\\" + BN); //TESTANDO NOVA FORMA DE COPIAR File origem = new File(caminhoarquivo); File destino = new File(caminhodestino); FileInputStream fis = new FileInputStream(origem); FileOutputStream fos = new FileOutputStream(destino); FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); long transferFrom = outChannel.transferFrom(inChannel, 0, inChannel.size()); fis.close(); fos.close(); inChannel.close(); outChannel.close(); // Thread.sleep(10); BN = BN.substring(0, BN.length() - 4); PdfContentByte cb = writer.getDirectContent(); int i = 0; while (i < reader.getNumberOfPages()) { montaraAquivo(caminhodestino).newPage(); i++; //PDFCONTETBYTE GERA UMA ESPECIE DE CODIGO DE BARRAS PdfContentByte under = writer.getDirectContentUnder(); PdfImportedPage page1 = writer.getImportedPage(reader, i); cb.addTemplate(page1, 0, i * 0.2f); //CARIMBO DA BN BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED); cb.beginText(); cb.setFontAndSize(bf, 14); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 32, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 22, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " | |", width / 6, 12, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0); cb.endText(); } montaraAquivo(caminhodestino).close(); writer.close(); reader.close(); origem.delete(); } catch (IOException | DocumentException ex) { } }
From source file:main.java.com.cts.ptms.carrier.ups.UPSHTTPClient.java
/** * This method Generate the shipping label as a PDF file */// w w w. j av a 2 s . c o m private String generateShippingLabelPDF(byte[] decoded, String trackingNumber, ShippingInfoDO shippingInfoDO, ShipmentRequest request) throws MalformedURLException, IOException, DocumentException { Document document = new Document(); PdfWriter writer; String URL = ""; try { String filename = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath() + trackingNumber + ShippingConstants.PDF_fILE; String path = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath() + trackingNumber + ShippingConstants.PNG_FILE; if (genReturnLabel) { filename = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath() + "Return_" + trackingNum + ShippingConstants.PDF_fILE; path = new UPSHTTPClient().getClass().getClassLoader().getResource("").getPath() + "Return_" + trackingNum + ShippingConstants.PNG_FILE; } else { trackingNum = trackingNumber; } filename = filename.replace(ShippingConstants.FILE_PATH, ""); path = path.replace(ShippingConstants.FILE_PATH, ShippingConstants.File_Path_Replace); OutputStream out1 = null; try { out1 = new BufferedOutputStream(new FileOutputStream(path)); out1.write(decoded); } finally { if (out1 != null) { out1.close(); } } File pdfFile = new File(filename); writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile)); document.open(); Image barcode = Image.getInstance(decoded); barcode.setBorder(50); barcode.scalePercent(40, 60); document.add(barcode); document.close(); writer.close(); URL = filename; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return URL; }
From source file:models.FileManager.java
public static Boolean makePDF(String fname, String wString) { com.itextpdf.text.Document document = new com.itextpdf.text.Document(); try {//from w w w . j ava 2 s . c o m PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fname)); document.open(); document.add(new Paragraph("Welcome AT MCQ EXAM")); document.add(new Paragraph("\n\n\n\n\n")); document.add(new Paragraph(wString)); document.close(); writer.close(); } catch (FileNotFoundException | DocumentException e) { return Boolean.FALSE; } return Boolean.TRUE; }
From source file:naprawa.praca.PracaController.java
public void akcjaDrukuj() { mapaUslug = getDaoFactory().getDaoDefect().pobierzUslugi(getConnection(), wybranyDefect); FileOutputStream file = null; File druk = null;/* w ww . j ava 2 s . c om*/ try { Document document = new Document(PageSize.A5, 0, 0, 0, 0); String userPath = System.getProperty("user.home"); druk = new File(userPath + "/Baks wydruki"); if (!druk.exists()) { druk.mkdirs(); } File wydruk = new File(druk + "/" + wybranyDefect.getInfoNaprawa() + ".pdf"); if (!wydruk.exists()) { try { wydruk.createNewFile(); } catch (IOException ex) { Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex); } } file = new FileOutputStream(wydruk); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(wydruk)); document.open(); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); table.setSpacingBefore(0f); table.setSpacingAfter(0f); PdfPTable tableO = new PdfPTable(2); tableO.setWidthPercentage(100); tableO.setSpacingBefore(0f); table.setSpacingAfter(0f); tableO.addCell(getNewCell( "BAK's Machine\nin. Baej Krzciuk\n26-800 Biaobrzegi\nul. Brzechwy 31\ntel. 509-281-487")); Image image = Image.getInstance(getClass().getClassLoader().getResource("baksZ.jpg")); tableO.addCell(image); table.addCell(tableO); PdfPCell cell1 = getNewCell( "Biaobrzegi, dn. " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(cell1); table.addCell(addTableCzesc()); table.addCell(addTableCzescService("Materiay", RodzajUslugi.MATERIAL)); table.addCell(addTableCzescService("Naprawa", RodzajUslugi.NAPRAWA)); PdfPTable tablePodsumowanie = new PdfPTable(3); tablePodsumowanie.setWidthPercentage(100); int[] width = { 8, 77, 15 }; tablePodsumowanie.setWidths(width); PdfPCell cell = getNewCell("Podsumowanie"); cell.setColspan(10); cell.setBorder(PdfPCell.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); tablePodsumowanie.addCell(cell); tablePodsumowanie.addCell(getNewCell("1.")); tablePodsumowanie.addCell(getNewCell("Czci")); tablePodsumowanie.addCell(getNewCell(wybranyDefect.getKosztCzesciS() + " z")); tablePodsumowanie.addCell(getNewCell("2.")); tablePodsumowanie.addCell(getNewCell("Materiay")); tablePodsumowanie.addCell(getNewCell(wybranyDefect.getKosztMaterialyS() + " z")); tablePodsumowanie.addCell(getNewCell("3.")); tablePodsumowanie.addCell(getNewCell("Naprawa")); tablePodsumowanie.addCell(getNewCell(wybranyDefect.getKosztNaprawyS() + " z")); tablePodsumowanie.addCell(getNewCell("")); tablePodsumowanie.addCell(getNewCell("RAZEM")); tablePodsumowanie.addCell(getNewCell(wybranyDefect.getKosztSumaS() + " z")); table.addCell(tablePodsumowanie); document.add(table); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } catch (FileNotFoundException ex) { Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex); BaksSessionBean.getInstance().fireMessage(widok, "Wydruk", "Pdf do ktrego chcesz zapisa wynik jest otwarty!\n Zamknij i sprbuj jeszcze raz."); } finally { try { file.close(); } catch (IOException ex) { Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex); } } Desktop desktop = null; if (Desktop.isDesktopSupported()) { desktop = Desktop.getDesktop(); try { desktop.open(druk); } catch (IOException ex) { Logger.getLogger(WyszukPlatnosciController.class.getName()).log(Level.SEVERE, null, ex); } } BaksSessionBean.getInstance().fireMessage(widok, "Zapis", "Wydruk zapisany w folderze: " + System.getProperty("user.home") + "/Baks wydruki"); }
From source file:net.sf.texprinter.generators.PDFGenerator.java
License:Open Source License
/** * Generates a PDF file from a Question object. * /*ww w .j a va 2s . c o m*/ * @param question The question. * @param filename The filename. */ public static void generate(Question question, String filename) { // wait window ProgressMessage pm = new ProgressMessage("TeXPrinter is printing your PDF file."); // start wait window //pm.start(); // log message log.log(Level.INFO, "Starting PDF generation of {0}.", filename); // define a new PDF document Document document = null; // define a new PDF writer PdfWriter writer = null; // lets try try { // create a new PDF document document = new Document(); // define a new PDF Writer writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // set the PDF version writer.setPdfVersion(PdfWriter.VERSION_1_6); // open the document document.open(); // set the title font Font titleFont = new Font(FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK); // set the chunk for the question title Chunk questionTitle = new Chunk(question.getQuestion().getTitle(), titleFont); // create a paragraph from that chunk Paragraph paragraphQuestionTitle = new Paragraph(questionTitle); // log message log.log(Level.INFO, "Adding the question title."); // add the question title to the document document.add(paragraphQuestionTitle); // set the asker font Font askerFont = new Font(FontFamily.HELVETICA, 10, Font.ITALIC, BaseColor.DARK_GRAY); // set the chunk for the asker Chunk questionAsker = new Chunk("Asked by " + question.getQuestion().getUser().getName() + " (" + question.getQuestion().getUser().getReputation() + ") on " + question.getQuestion().getDate() + " (" + String.valueOf(question.getQuestion().getVotes()) + (question.getQuestion().getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // create a paragraph from that chunk Paragraph paragraphQuestionAsker = new Paragraph(questionAsker); // log message log.log(Level.INFO, "Adding both asker and reputation."); // add the asker to the document document.add(paragraphQuestionAsker); // create a line separator LineSeparator line = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -5); // add the line to the document document.add(line); // add a new line document.add(Chunk.NEWLINE); // create a list of elements from the question objects List<Element> questionTextObjects = getPostText(question.getQuestion().getText()); // log message log.log(Level.INFO, "Adding the question text."); // for each element for (Element questionTextObject : questionTextObjects) { // add it to the document document.add(questionTextObject); } // add a new line document.add(Chunk.NEWLINE); // create a new font for the comments title Font commentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK); // create a new chunk based on that font Chunk commentsTitle = new Chunk( "This question has " + question.getQuestion().getComments().size() + ((question.getQuestion().getComments().size() == 1) ? " comment:" : " comments:"), commentsTitleFont); // create a paragraph from that chunk Paragraph paragraphCommentsTitle = new Paragraph(commentsTitle); // if there are comments to this question if (!question.getQuestion().getComments().isEmpty()) { // log message log.log(Level.INFO, "Adding the question comments."); // add that paragraph to the document document.add(paragraphCommentsTitle); // add a new line document.add(Chunk.NEWLINE); // get all the comments List<Comment> questionComments = question.getQuestion().getComments(); // for each comment for (Comment questionComment : questionComments) { // get the elements of the comment text List<Element> questionCommentObjects = getPostText(questionComment.getText()); // for each element for (Element questionCommentObject : questionCommentObjects) { // add it to the document document.add(questionCommentObject); } // create a new paragraph about the comment author Paragraph paragraphCommentAuthor = new Paragraph(questionComment.getAuthor() + " on " + questionComment.getDate() + " (" + String.valueOf(questionComment.getVotes()) + (questionComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // set the alignment to the right paragraphCommentAuthor.setAlignment(Element.ALIGN_RIGHT); // add the paragraph to the document document.add(paragraphCommentAuthor); // add a new line document.add(Chunk.NEWLINE); } } // add a line separator document.add(line); // add two new lines document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); // get the list of answers List<Post> answersList = question.getAnswers(); // if there are no answers if (answersList.isEmpty()) { // log message log.log(Level.INFO, "This question has no answers."); // create a new chunk Chunk noAnswersTitle = new Chunk("Sorry, this question has no answers yet.", titleFont); // create a paragraph from that chunk Paragraph paragraphNoAnswersTitle = new Paragraph(noAnswersTitle); // add the paragraph to the document document.add(paragraphNoAnswersTitle); } else { // log message log.log(Level.INFO, "Adding answers."); // there are answers, so create a counter for answers int answerCount = 1; // for each answer for (Post answer : answersList) { // log message log.log(Level.INFO, "Adding answer {0}.", answerCount); // set the message text as empty String answerAccepted = ""; // if the answer is accepted if (answer.isAccepted()) { // add that to the message answerAccepted = " - Marked as accepted."; } // create a new chunk Chunk answerTitle = new Chunk("Answer #" + answerCount, titleFont); // create a paragraph from that chunk Paragraph paragraphAnswerTitle = new Paragraph(answerTitle); // add the paragraph to the document document.add(paragraphAnswerTitle); // increase the counter answerCount++; // create a new chunk Chunk questionAnswerer = new Chunk("Answered by " + answer.getUser().getName() + " (" + answer.getUser().getReputation() + ") on " + answer.getDate() + answerAccepted + " (" + String.valueOf(answer.getVotes()) + (answer.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // create a paragraph from that chunk Paragraph paragraphQuestionAnswerer = new Paragraph(questionAnswerer); // add that paragraph to the document document.add(paragraphQuestionAnswerer); // add a line separator document.add(line); // add a new line document.add(Chunk.NEWLINE); // create a list of elements from the answer text List<Element> answerTextObjects = getPostText(answer.getText()); // for each element for (Element answerTextObject : answerTextObjects) { // add it to the document document.add(answerTextObject); } // add a new line document.add(Chunk.NEWLINE); // create a new font style Font answerCommentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK); // create a new chunk Chunk answerCommentsTitle = new Chunk( "This answer has " + answer.getComments().size() + ((answer.getComments().size() == 1) ? " comment:" : " comments:"), answerCommentsTitleFont); // create a paragraph from that chunk Paragraph paragraphAnswerCommentsTitle = new Paragraph(answerCommentsTitle); // if there are comments for that answer if (!answer.getComments().isEmpty()) { // log message log.log(Level.INFO, "Adding comments for answer {0}.", (answerCount - 1)); // add that paragraph to the document document.add(paragraphAnswerCommentsTitle); // add a new line document.add(Chunk.NEWLINE); // get all the comments List<Comment> answerComments = answer.getComments(); // for each comment for (Comment answerComment : answerComments) { // create a list of elements from the comment text List<Element> answerCommentObjects = getPostText(answerComment.getText()); // for each element for (Element answerCommentObject : answerCommentObjects) { // add it to the document document.add(answerCommentObject); } // create a new paragraph for the comment author Paragraph paragraphAnswerCommentAuthor = new Paragraph( answerComment.getAuthor() + " on " + answerComment.getDate() + " (" + String.valueOf(answerComment.getVotes()) + (answerComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont); // set the aligment to the right paragraphAnswerCommentAuthor.setAlignment(Element.ALIGN_RIGHT); // add the paragraph to the document document.add(paragraphAnswerCommentAuthor); // add a new line document.add(Chunk.NEWLINE); } } // add a line separator document.add(line); // add two new lines document.add(Chunk.NEWLINE); document.add(Chunk.NEWLINE); } } // log message log.log(Level.INFO, "PDF generation complete, closing {0}.", filename); // close the document document.close(); // stop wait window pm.interrupt(); } catch (IOException ioexception) { // stop wait window pm.interrupt(); // log message log.log(Level.SEVERE, "An IO error occurred while trying to create the PDF file. MESSAGE: {0}", StringUtils.printStackTrace(ioexception)); // critical error, exit Dialogs.showExceptionWindow(); } catch (Exception exception) { // log message log.log(Level.SEVERE, "A generic error occurred while trying to create the PDF file. MESSAGE: {0}", StringUtils.printStackTrace(exception)); // log message log.log(Level.INFO, "I will try to remove the remaining PDF file."); try { // log message log.log(Level.INFO, "Closing both document and writer."); // close the document document.close(); // close the writer writer.close(); } catch (Exception ex) { // log message log.log(Level.WARNING, "I could not close either document or writer. MESSAGE: {0}", StringUtils.printStackTrace(ex)); } try { // reference problematic file File target = new File(filename); // log message log.log(Level.INFO, "Opening problematic file {0}.", filename); // check if file exists if (target.exists()) { // log message log.log(Level.INFO, "File exists, trying to delete it."); // trying to remove it if (target.delete()) { // log message log.log(Level.INFO, "File {0} was successfully removed.", filename); } else { // log message log.log(Level.SEVERE, "File {0} could not be removed.", filename); } } } catch (SecurityException se) { // log message log.log(Level.SEVERE, "A security exception was raised. MESSAGE: {0}", StringUtils.printStackTrace(se)); } // stop wait window pm.interrupt(); // critical error, exit Dialogs.showExceptionWindow(); } }
From source file:numerical.CramersRule.java
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_saveActionPerformed JFileChooser jfc = new JFileChooser(); jfc.setCurrentDirectory(new File("/My Documents")); int return_val = jfc.showSaveDialog(rootPane); if (return_val == JFileChooser.APPROVE_OPTION) { Document doc = new Document(); try {//from w ww . j av a 2 s .co m jfc.getSelectedFile(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(jfc.getSelectedFile() + ".pdf")); doc.open(); Font f = new Font(Font.FontFamily.TIMES_ROMAN, 12.0f, Font.NORMAL, BaseColor.BLACK); Font f1 = new Font(Font.FontFamily.TIMES_ROMAN, 18.0f, Font.BOLD, BaseColor.BLACK); Paragraph paragraph = new Paragraph(null, f); Paragraph title = new Paragraph(null, f1); title.add("Cramers Rule\n"); paragraph.add(txt_result.getText()); doc.add(title); doc.add(paragraph); doc.close(); writer.close(); JOptionPane.showMessageDialog(rootPane, "Successfully saved!"); } catch (FileNotFoundException | DocumentException | HeadlessException e) { System.err.println(e); } } }
From source file:numerical.Determinants.java
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_saveActionPerformed JFileChooser jfc = new JFileChooser(); jfc.setCurrentDirectory(new File("/My Documents")); int return_val = jfc.showSaveDialog(rootPane); if (return_val == JFileChooser.APPROVE_OPTION) { Document doc = new Document(); try {//from w w w .ja v a 2 s . c o m jfc.getSelectedFile(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(jfc.getSelectedFile() + ".pdf")); doc.open(); Font f = new Font(Font.FontFamily.TIMES_ROMAN, 12.0f, Font.NORMAL, BaseColor.BLACK); Font f1 = new Font(Font.FontFamily.TIMES_ROMAN, 18.0f, Font.BOLD, BaseColor.BLACK); Paragraph paragraph = new Paragraph(null, f); Paragraph title = new Paragraph(null, f1); title.add("Determinants \n"); paragraph.add(txt_result.getText()); doc.add(title); doc.add(paragraph); doc.close(); writer.close(); JOptionPane.showMessageDialog(rootPane, "Successfully saved!"); } catch (FileNotFoundException | DocumentException | HeadlessException e) { System.err.println(e); } } }
From source file:numerical.Fibonnaci.java
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_saveActionPerformed JFileChooser jfc = new JFileChooser(); jfc.setCurrentDirectory(new File("/My Documents")); int return_val = jfc.showSaveDialog(rootPane); if (return_val == JFileChooser.APPROVE_OPTION) { Document doc = new Document(); try {//from w w w. ja v a2s. c o m jfc.getSelectedFile(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(jfc.getSelectedFile() + ".pdf")); doc.open(); Font f = new Font(Font.FontFamily.TIMES_ROMAN, 12.0f, Font.NORMAL, BaseColor.BLACK); Font f1 = new Font(Font.FontFamily.TIMES_ROMAN, 18.0f, Font.BOLD, BaseColor.BLACK); Paragraph paragraph = new Paragraph(null, f); Paragraph title = new Paragraph(null, f1); title.add("Fibonnaci\n"); paragraph.add("Sequence number: " + count + "\n"); paragraph.add("Result: "); paragraph.add(txt_result.getText()); doc.add(title); doc.add(paragraph); doc.close(); writer.close(); JOptionPane.showMessageDialog(rootPane, "Successfully saved!"); } catch (FileNotFoundException | DocumentException | HeadlessException e) { System.err.println(e); } } }
From source file:nz.ac.waikato.cms.doc.OverlayFilename.java
License:Open Source License
/** * Performs the overlay./*from w ww . j av a2 s.co m*/ * * @param input the input file/dir * @param output the output file/dir * @param vpos the vertical position * @param hpos the horizontal position * @param stripPath whether to strip the path * @param stripExt whether to strip the extension * @param pages the array of pages (1-based) to add the overlay to, null for all * @param evenPages whether to enforce even pages in the document * @return true if successfully overlay */ public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt, int[] pages, boolean evenPages) { PdfReader reader; PdfStamper stamper; FileOutputStream fos; PdfContentByte canvas; int i; String text; int numPages; File tmpFile; Document document; PdfWriter writer; PdfImportedPage page; PdfContentByte cb; reader = null; stamper = null; fos = null; numPages = -1; try { reader = new PdfReader(input.getAbsolutePath()); fos = new FileOutputStream(output.getAbsolutePath()); stamper = new PdfStamper(reader, fos); numPages = reader.getNumberOfPages(); if (pages == null) { pages = new int[reader.getNumberOfPages()]; for (i = 0; i < pages.length; i++) pages[i] = i + 1; } if (stripPath) text = input.getName(); else text = input.getAbsolutePath(); if (stripExt) text = text.replaceFirst("\\.[pP][dD][fF]$", ""); for (i = 0; i < pages.length; i++) { canvas = stamper.getOverContent(pages[i]); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f); } } catch (Exception e) { System.err.println("Failed to process " + input + ":"); e.printStackTrace(); return false; } finally { try { if (stamper != null) stamper.close(); } catch (Exception e) { // ignored } try { if (reader != null) reader.close(); } catch (Exception e) { // ignored } try { if (fos != null) { fos.flush(); fos.close(); } } catch (Exception e) { // ignored } } // enforce even pages? if (evenPages && (numPages > 0) && (numPages % 2 == 1)) { reader = null; fos = null; writer = null; tmpFile = new File(output.getAbsolutePath() + "tmp"); try { if (!output.renameTo(tmpFile)) { System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!"); return false; } reader = new PdfReader(tmpFile.getAbsolutePath()); document = new Document(reader.getPageSize(1)); fos = new FileOutputStream(output.getAbsoluteFile()); writer = PdfWriter.getInstance(document, fos); document.open(); document.addCreationDate(); document.addAuthor(System.getProperty("user.name")); cb = writer.getDirectContent(); for (i = 0; i < reader.getNumberOfPages(); i++) { page = writer.getImportedPage(reader, i + 1); document.newPage(); cb.addTemplate(page, 0, 0); } document.newPage(); document.add(new Paragraph(" ")); // fake content document.close(); } catch (Exception e) { System.err.println("Failed to process " + tmpFile + ":"); e.printStackTrace(); return false; } finally { try { if (fos != null) { fos.flush(); fos.close(); } } catch (Exception e) { // ignored } try { if (reader != null) reader.close(); } catch (Exception e) { // ignored } try { if (writer != null) writer.close(); } catch (Exception e) { // ignored } if (tmpFile.exists()) { try { tmpFile.delete(); } catch (Exception e) { // ignored } } } } return true; }
From source file:org.alex73.skarynka.scan.process.pdf.PdfCreator.java
License:Open Source License
public static void create(File outFile, File[] jpegs) throws Exception { Document pdf = new Document(); pdf.setMargins(0, 0, 0, 0);/*w w w . j av a2 s. co m*/ Image image0 = Jpeg.getInstance(jpegs[0].getPath()); pdf.setPageSize(new Rectangle(0, 0, image0.getScaledWidth(), image0.getScaledHeight())); PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(outFile)); pdf.open(); float minWidth = Float.MAX_VALUE, maxWidth = Float.MIN_VALUE, minHeight = Float.MAX_VALUE, maxHeight = Float.MIN_VALUE; for (File jpeg : jpegs) { Image image = Jpeg.getInstance(jpeg.getPath()); float width, height; width = image.getScaledWidth(); height = image.getScaledHeight(); minWidth = Math.min(minWidth, width); maxWidth = Math.max(maxWidth, width); minHeight = Math.min(minHeight, height); maxHeight = Math.max(maxHeight, height); pdf.setPageSize(new Rectangle(0, 0, width, height)); pdf.newPage(); pdf.add(image); } pdf.close(); writer.flush(); writer.close(); }