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:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java
License:Open Source License
/** * This method creates multi page pdf using IText. * /*from w ww . j av a2 s. co m*/ * @param batchInstanceThread {@link BatchInstanceThread} * @param pages11 {@link String} * @param widthOfPdfPage int * @param heightOfPdfPage int */ public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final String[] pages11, final int widthOfPdfPage, final int heightOfPdfPage) { if (pages11 != null && pages11.length > 0) { this.pages = new String[pages11.length]; this.pages = pages11.clone(); batchInstanceThread.add(new AbstractRunnable() { @Override public void run() { String pdf = pages[pages.length - 1]; Document document = null; PdfWriter writer = null; RandomAccessFileOrArray randomAccessArray = null; try { document = new Document(PageSize.LETTER, 0, 0, 0, 0); writer = PdfWriter.getInstance(document, new FileOutputStream(pdf)); document.open(); int comps = 1; int totalTiffImages = pages.length - 1; int index = 0; while (index < totalTiffImages) { randomAccessArray = new RandomAccessFileOrArray(pages[index]); comps = TiffImage.getNumberOfPages(randomAccessArray); // Conversion statement for (int tiffPageNumber = 0; tiffPageNumber < comps; ++tiffPageNumber) { Image img = TiffImage.getTiffImage(randomAccessArray, tiffPageNumber + 1); img.scaleToFit(widthOfPdfPage, heightOfPdfPage); document.add(img); document.newPage(); } index++; } } catch (Exception e) { LOGGER.error("Error while creating pdf using iText" + e.getMessage(), e); //pdf = null; } finally { try { if (document != null) { document.close(); } if (writer != null) { writer.close(); } if (randomAccessArray != null) { randomAccessArray.close(); } } catch (Exception e) { LOGGER.error("Error while closing I/O streams for write PDF. " + e.getMessage()); } } } }); } }
From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java
License:Open Source License
/** * The <code>MultiPageExecutor</code> method creates multi page searchable pdf using IText. * /*from w w w .jav a2 s .c o m*/ * @param batchInstanceThread {@link BatchInstanceThread} thread instance of batch * @param imageHtmlMap {@link Map} map containing image url with corresponding hocr * @param isColoredPDF true for colored image pdf else otherwise * @param isSearchablePDF true for searchable pdf else otherwise * @param pdfFilePath {@link String} path where new pdf has to be created * @param widthOfLine Integer for line width to be used */ public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final Map<String, HocrPage> imageHtmlMap, final boolean isColoredPDF, final boolean isSearchablePDF, final String pdfFilePath, final int widthOfLine, final String[] pages) { if (imageHtmlMap != null && !imageHtmlMap.isEmpty()) { this.pages = new String[pages.length]; this.pages = pages.clone(); batchInstanceThread.add(new AbstractRunnable() { @Override public void run() { String pdf = pdfFilePath; Document document = null; PdfWriter writer = null; FileOutputStream fileOutputStream = null; boolean isPdfSearchable = isSearchablePDF; boolean isColoredImage = isColoredPDF; LOGGER.info("is searchable pdf: " + isPdfSearchable + ", is Colored Image: " + isColoredImage); try { document = new Document(PageSize.LETTER, 0, 0, 0, 0); fileOutputStream = new FileOutputStream(pdf); writer = PdfWriter.getInstance(document, fileOutputStream); document.open(); Set<String> imageSet = imageHtmlMap.keySet(); for (String imageUrl : imageSet) { HocrPage hocrPage = imageHtmlMap.get(imageUrl); String newImageUrl = getCompressedImage(isColoredImage, imageUrl); LOGGER.info("New Image URL: " + newImageUrl); addImageToPdf(writer, hocrPage, newImageUrl, isPdfSearchable, widthOfLine); document.newPage(); (new File(newImageUrl)).delete(); } } catch (FileNotFoundException fileNotFoundException) { LOGGER.error("Error occurred while creating pdf " + pdf + " : " + fileNotFoundException.toString()); } catch (DocumentException documentException) { LOGGER.error( "Error occurred while creating pdf " + pdf + " : " + documentException.toString()); } finally { if (document != null && document.isOpen()) { document.close(); } // Closing pdf writer if (null != writer) { writer.close(); } // Closing file output stream of pdf if (null != fileOutputStream) { try { fileOutputStream.close(); } catch (IOException ioException) { LOGGER.error("Error occurred while closing stream for pdf " + pdf + " : " + ioException.toString()); } } } } }); } }
From source file:com.ephesoft.dcma.util.PDFUtil.java
License:Open Source License
/** * The <code>closePassedStream</code> method closes the stream passed. * /* w w w . j a v a2 s.com*/ * @param reader {@link PdfReader} * @param document {@link Document} * @param contentByte {@link PdfContentByte} * @param writer {@link PdfWriter} * @param fileInputStream {@link FileInputStream} * @param fileOutputStream {@link FileOutputStream} * @throws IOException {@link} if unable to close input or output stream */ private static void closePassedStream(final PdfReader reader, final Document document, final PdfContentByte contentByte, final PdfWriter writer, final FileInputStream fileInputStream, final FileOutputStream fileOutputStream) throws IOException { if (null != reader) { reader.close(); } if (null != document) { document.close(); } if (null != contentByte) { contentByte.closePath(); } if (null != writer) { writer.close(); } if (null != fileInputStream) { fileInputStream.close(); } if (null != fileOutputStream) { fileOutputStream.flush(); fileOutputStream.close(); } }
From source file:com.khepry.frackhem.fxml.FracKhemGUIController.java
License:Apache License
private void saveTextAsPDF(String content, File file) throws FileNotFoundException, DocumentException, IOException, InterruptedException { Document document = new Document(PageSize.A4.rotate()); PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open();/*from w ww. j av a 2s .com*/ document.addAuthor("Author of the Doc"); document.addCreator("Creator of the Doc"); document.addSubject("Subject of the Doc"); document.addCreationDate(); document.addTitle(file.getName()); String html = htmlHeader.concat(markdown4jProcessor.process(content.trim())); // XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, new ByteArrayInputStream(html.getBytes("UTF-8")), this.getClass().getResourceAsStream(cssFileFullPath)); XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, new ByteArrayInputStream(html.getBytes("UTF-8"))); document.close(); pdfWriter.close(); displayFile(file.getAbsolutePath(), sleepMillis); }
From source file:com.masscustsoft.service.ToPdf.java
License:Open Source License
private void createPdf(Map rpt, Map<String, String> i18n, File pdf) throws Exception { OutputStream out = new FileOutputStream(pdf); ThreadHelper.set("_fonts_", new HashMap<String, BaseFont>()); ThreadHelper.set("_defaultFont_", BaseFont.createFont()); String pageSize = MapUtil.getStr(rpt, "pageSize", "A4"); int defaultFontSize = MapUtil.getInt(rpt, "defaultFontSize", 6); ThreadHelper.set("_defaultFontSize_", defaultFontSize); ThreadHelper.set("_rpt_", rpt); int i = pageSize.indexOf(';'); String margins = "36 36 36 36"; if (i > 0) { margins = pageSize.substring(i + 1); pageSize = pageSize.substring(0, i); }/*ww w. j a v a2 s.c o m*/ boolean rotate = false; if (pageSize.startsWith("@")) { rotate = true; pageSize = pageSize.substring(1); } Rectangle pSize = PageSize.getRectangle(pageSize); if (rotate) pSize = pSize.rotate(); String mars[] = margins.split(" "); float ml = 0, mt = 0, mr = 0, mb = 0; mr = mt = mb = ml = LightUtil.decodeFloat(mars[0]); if (mars.length > 1) { mt = mb = LightUtil.decodeFloat(mars[1]); } if (mars.length > 2) { mr = LightUtil.decodeFloat(mars[2]); } if (mars.length > 3) { mb = LightUtil.decodeFloat(mars[3]); } Document doc = new Document(pSize, ml, mr, mt, mb); MapUtil.setIfStr(rpt, "author", doc, "addAuthor"); MapUtil.setIfStr(rpt, "creator", doc, "addCreator"); MapUtil.setIfStr(rpt, "title", doc, "addTitle"); MapUtil.setIfStr(rpt, "keyWords", doc, "addKeywords"); MapUtil.setIfStr(rpt, "subject", doc, "addSubject"); PdfWriter writer = PdfWriter.getInstance(doc, out); writer.setPageEvent(this); writer.setStrictImageSequence(true); ThreadHelper.set("_writer_", writer); ThreadHelper.set("_doc_", doc); doc.open(); List<Map> items = (List) rpt.get("items"); for (Map row : items) { Element el = getElement(row); if (el != null) doc.add(el); } doc.close(); out.close(); writer.close(); ThreadHelper.set("_writer_", null); ThreadHelper.set("_doc_", null); }
From source file:com.mycompany.mavenproject1.Createpdf.java
public void createPDF(String pdfFilename) { Document doc = new Document(); PdfWriter docWriter = null; initializeFonts();//from ww w. jav a2 s .c om try { String path = "C:\\Users\\Thaskioglu\\Downloads\\" + pdfFilename; docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path)); doc.addAuthor("FabulousCar"); doc.addCreationDate(); doc.addProducer(); doc.addCreator("FabulousCar"); doc.addTitle("Invoice"); doc.setPageSize(PageSize.LETTER); doc.open(); PdfContentByte cb = docWriter.getDirectContent(); boolean beginPage = true; int y = 0; for (int i = 0; i < 100; i++) { if (beginPage) { beginPage = false; generateLayout(doc, cb); generateHeader(doc, cb); y = 615; } generateDetail(doc, cb, i, y); y = y - 15; if (y < 50) { printPageNumber(cb); doc.newPage(); beginPage = true; } } printPageNumber(cb); } catch (DocumentException dex) { dex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (doc != null) { doc.close(); } if (docWriter != null) { docWriter.close(); } } }
From source file:com.mycompany.peram_inclassexam.WritePDFFile.java
public void createPDF(AccountDetails account) throws DocumentException, FileNotFoundException, BadElementException, IOException { Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter write = PdfWriter.getInstance(document, new FileOutputStream(account.getLastName() + "_output.pdf")); document.open();//ww w . j av a 2 s . c o m Image image = Image.getInstance("image.png"); image.scaleToFit(450f, 1800f); document.add(image); document.add(new Paragraph( "--------------------------------------------------------------------------------------------------------------------------")); Paragraph welcomeParagraph = new Paragraph( "Welcome! " + account.getFirstName() + " " + account.getLastName() + "!"); welcomeParagraph.setSpacingBefore(50); document.add(welcomeParagraph); String firstName = "First Name: " + account.getFirstName(); String lastName = "Last Name: " + account.getLastName(); String acctNumber = "Account Number: " + account.getAccountNo(); String acctBalance = String.format("Account Balance: $%.1f", account.getAccountBalance()); Paragraph detailsPara = new Paragraph("Below are your Account Details:\n" + firstName + "\n" + lastName + "\n" + acctNumber + "\n" + acctBalance); detailsPara.setIndentationLeft(30); detailsPara.setSpacingBefore(20); document.add(detailsPara); document.close(); write.close(); }
From source file:com.netsteadfast.greenstep.bsc.command.KpiReportPdfCommand.java
License:Apache License
private String createPdf(Context context) throws Exception { BscReportPropertyUtils.loadData();/*from w w w.j ava 2 s . c o m*/ BscReportSupportUtils.loadExpression(); // 2015-04-18 add String visionOid = (String) context.get("visionOid"); VisionVO vision = null; BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context); for (VisionVO visionObj : treeObj.getVisions()) { if (visionObj.getOid().equals(visionOid)) { vision = visionObj; } } FontFactory.register(BscConstants.PDF_ITEXT_FONT); String fileName = UUID.randomUUID().toString() + ".pdf"; String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName; OutputStream os = new FileOutputStream(fileFullPath); //Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); Document document = new Document(PageSize.A4, 10, 10, 10, 10); document.left(100f); document.top(150f); PdfWriter writer = PdfWriter.getInstance(document, os); document.open(); int dateRangeRows = 4 + vision.getPerspectives().get(0).getObjectives().get(0).getKpis().get(0) .getDateRangeScores().size(); PdfPTable table = new PdfPTable(MAX_COLSPAN); PdfPTable dateRangeTable = new PdfPTable(dateRangeRows); PdfPTable chartsTable = new PdfPTable(2); PdfPTable signTable = new PdfPTable(1); table.setWidthPercentage(100f); dateRangeTable.setWidthPercentage(100f); chartsTable.setWidthPercentage(100f); signTable.setWidthPercentage(100f); this.createHead(table, vision); this.createBody(table, vision); this.createDateRange(dateRangeTable, vision, context, dateRangeRows); this.putCharts(chartsTable, context); this.putSignature(signTable, context); document.add(chartsTable); document.add(table); document.add(dateRangeTable); document.add(signTable); document.close(); writer.close(); os.flush(); os.close(); os = null; File file = new File(fileFullPath); String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "kpi-report.pdf"); file = null; return oid; }
From source file:com.netsteadfast.greenstep.bsc.command.OrganizationReportPdfCommand.java
License:Apache License
private String createPdf(Context context) throws Exception { BscReportPropertyUtils.loadData();/*from www . jav a 2s.c o m*/ String visionOid = (String) context.get("visionOid"); VisionVO vision = null; BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context); for (VisionVO visionObj : treeObj.getVisions()) { if (visionObj.getOid().equals(visionOid)) { vision = visionObj; } } FontFactory.register(BscConstants.PDF_ITEXT_FONT); String fileName = UUID.randomUUID().toString() + ".pdf"; String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName; OutputStream os = new FileOutputStream(fileFullPath); Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); document.left(100f); document.top(150f); PdfWriter writer = PdfWriter.getInstance(document, os); document.open(); PdfPTable table = new PdfPTable(MAX_COLSPAN); table.setWidthPercentage(100f); PdfPTable signTable = new PdfPTable(1); signTable.setWidthPercentage(100f); this.createHead(table, vision, context); this.createBody(table, vision); this.putSignature(signTable, context); document.add(table); document.add(signTable); document.close(); writer.close(); os.flush(); os.close(); os = null; File file = new File(fileFullPath); String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "department-report.pdf"); file = null; return oid; }
From source file:com.netsteadfast.greenstep.bsc.command.PersonalReportPdfCommand.java
License:Apache License
private String createPdf(Context context) throws Exception { BscReportPropertyUtils.loadData();/* ww w.j av a 2s .c om*/ String visionOid = (String) context.get("visionOid"); VisionVO vision = null; BscStructTreeObj treeObj = (BscStructTreeObj) this.getResult(context); for (VisionVO visionObj : treeObj.getVisions()) { if (visionObj.getOid().equals(visionOid)) { vision = visionObj; } } FontFactory.register(BscConstants.PDF_ITEXT_FONT); String fileName = UUID.randomUUID().toString() + ".pdf"; String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName; OutputStream os = new FileOutputStream(fileFullPath); Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); document.left(100f); document.top(150f); PdfWriter writer = PdfWriter.getInstance(document, os); document.open(); PdfPTable table = new PdfPTable(MAX_COLSPAN); table.setWidthPercentage(100f); PdfPTable signTable = new PdfPTable(1); signTable.setWidthPercentage(100f); this.createHead(table, vision, context); this.createBody(table, vision); this.createFoot(table, context); this.putSignature(signTable, context); document.add(table); document.add(signTable); document.close(); writer.close(); os.flush(); os.close(); os = null; File file = new File(fileFullPath); String oid = UploadSupportUtils.create(Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "personal-report.pdf"); file = null; return oid; }