List of usage examples for com.lowagie.text.pdf PdfWriter getInstance
public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException
PdfWriter
. From source file:mx.dr.util.report.impl.PdfService.java
License:Open Source License
/** * @see mx.dr.util.report.IPdfService#doMultiReport(List, OutputStream) *//* www . j a v a2 s . c o m*/ public void doMultiReport(List<Object> lista, OutputStream out) throws Exception { DRPdfDocument anonDoc = null; for (Object o : lista) { anonDoc = o.getClass().getAnnotation(DRPdfDocument.class); break; } Document doc = null; if (anonDoc != null) { doc = new Document(new Rectangle(anonDoc.height(), anonDoc.width()), 0, 0, 0, 0); } else { doc = new Document(PageSize.LETTER, 0, 0, 0, 0); } PdfWriter.getInstance(doc, out); doc.open(); Object dto; for (int i = 0; i < lista.size(); i++) { dto = lista.get(i); if (i > 0) { doc.newPage(); } estampaEtiqueta(doc, dto, null, null); } doc.close(); }
From source file:mx.dr.util.report.impl.PdfService.java
License:Open Source License
/** * @see mx.dr.util.report.IPdfService#doReport(Object, OutputStream) *//*from w ww. j a va 2 s . com*/ public void doReport(Object dto, OutputStream out) throws Exception { DRPdfDocument anonDoc = null; anonDoc = dto.getClass().getAnnotation(DRPdfDocument.class); Document doc = null; if (anonDoc != null) { doc = new Document(new Rectangle(anonDoc.height(), anonDoc.width()), 0, 0, 0, 0); } else { doc = new Document(PageSize.LETTER, 0, 0, 0, 0); } PdfWriter.getInstance(doc, out); doc.open(); estampaEtiqueta(doc, dto, null, null); doc.close(); }
From source file:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java
License:Open Source License
public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception { URL inputHOCRFile = null;//from w w w . j a v a 2s .co m FileOutputStream outputPDFStream = null; // The resolution of a PDF file (using iText) is 72pt per inch float pointsPerInch = 72.0f; Source source = null; StartTag pageTag = null; Pattern imagePattern = null; Matcher imageMatcher = null; // Load the image Image pageImage = null; float dotsPerPointX; float dotsPerPointY; float pageImagePixelHeight; Document pdfDocument = null; PdfWriter pdfWriter = null; Font defaultFont = null; PdfContentByte cb = null; Pattern bboxPattern = null; Pattern bboxCoordinatePattern = null; StartTag ocrLineTag = null; try { try { inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath()); } catch (MalformedURLException e) { throw e; } try { outputPDFStream = new FileOutputStream(fPdf); } catch (FileNotFoundException e) { throw e; } // Using the jericho library to parse the HTML file source = new Source(inputHOCRFile); // Find the tag of class ocr_page in order to load the scanned image pageTag = source.findNextStartTag(0, "class", "ocr_page", false); imagePattern = Pattern.compile("image\\s+([^;]+)"); imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title")); if (!imageMatcher.find()) { throw new Exception("Could not find a tag of class \"ocr_page\", aborting."); } try { pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath())); } catch (MalformedURLException e) { throw e; } dotsPerPointX = pageImage.getDpiX() / pointsPerInch; dotsPerPointY = pageImage.getDpiY() / pointsPerInch; pageImagePixelHeight = pageImage.getHeight(); pdfDocument = new Document( new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY)); pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream); pdfDocument.open(); // first define a standard font for our text defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK); // Put the text behind the picture (reverse for debugging) cb = pdfWriter.getDirectContentUnder(); //PdfContentByte cb = pdfWriter.getDirectContent(); pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY); pageImage.setAbsolutePosition(0, 0); // Put the image in front of the text (reverse for debugging) pdfWriter.getDirectContent().addImage(pageImage); //pdfWriter.getDirectContentUnder().addImage(pageImage); // In order to place text behind the recognised text snippets we are interested in the bbox property bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}"); // This pattern separates the coordinates of the bbox property bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)"); // Only tags of the ocr_line class are interesting ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false); while (ocrLineTag != null) { au.id.jericho.lib.html.Element lineElement = ocrLineTag.getElement(); Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title")); if (bboxMatcher.find()) { // We found a tag of the ocr_line class containing a bbox property Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group()); bboxCoordinateMatcher.find(); int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))), Integer.parseInt((bboxCoordinateMatcher.group(2))), Integer.parseInt((bboxCoordinateMatcher.group(3))), Integer.parseInt((bboxCoordinateMatcher.group(4))) }; String line = lineElement.getContent().extractText(); // float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX; float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY; // Put the text into the PDF cb.beginText(); // Comment the next line to debug the PDF output (visible Text) cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); // TODO: Scale the text width to fit the OCR bbox cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt)); cb.moveText((float) (coordinates[0] / dotsPerPointX), (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY)); cb.showText(line); cb.endText(); } ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false); } } catch (NumberFormatException e) { throw e; } catch (MalformedURLException e) { throw e; } catch (FileNotFoundException e) { throw e; } catch (BadElementException e) { throw e; } catch (IOException e) { throw e; } catch (DocumentException e) { throw e; } catch (Exception e) { throw e; } finally { if (pdfDocument != null) { pdfDocument.close(); } if (outputPDFStream != null) { outputPDFStream.close(); } } }
From source file:net.algem.contact.TeacherCtrl.java
License:Open Source License
private File getFollowUpAsPDF(String userId, String from, String to) throws IOException, BadElementException, DocumentException { String path = "/tmp/" + "suivi-" + userId + ".pdf"; File f = new File(path); LOGGER.log(Level.INFO, f.getName()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Document document = new Document(PageSize.A4.rotate()); PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open() document.open();/* ww w. j ava 2 s . co m*/ PdfPTable table = new PdfPTable(10); table.setWidthPercentage(100); table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f }); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false); BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false); Font normalFont = new Font(bf, 10); Font boldFont = new Font(bfb, 10); String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE); String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE); String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " " + organization.get("name.label"); String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to; PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont)); headerCell.setBackgroundColor(Color.LIGHT_GRAY); headerCell.setColspan(10); table.addCell(headerCell); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("student.label", null, CTX_LOCALE), boldFont))); String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE); table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont))); List<ScheduleElement> items = getFollowUpSchedules(userId, from, to); //LOGGER.log(Level.INFO, items.toString()); for (ScheduleElement e : items) { List<ScheduleRangeElement> ranges = new ArrayList<ScheduleRangeElement>( (Collection<? extends ScheduleRangeElement>) e.getRanges()); for (ScheduleRangeElement r : ranges) { String status = CommonDao.getAbsenceFromNumberStatus(r.getFollowUp().getStatus()); String note = r.getFollowUp().getNote(); String content1 = r.getFollowUp().getContent(); String content2 = e.getFollowUp().getContent(); table.addCell(new Phrase(e.getDateFr().toString(), normalFont)); table.addCell(new Phrase(r.getStart() + "-" + r.getEnd(), normalFont)); table.addCell(new Phrase(new Hour(r.getLength()).toString(), normalFont)); table.addCell(new Phrase(e.getDetail().get("room").getName(), normalFont)); table.addCell(new Phrase(e.getDetail().get("course").getName(), normalFont)); table.addCell(new Phrase(r.getPerson().getFirstName() + " " + r.getPerson().getName(), normalFont)); table.addCell(new Phrase(status, normalFont)); table.addCell(new Phrase(note == null ? "" : note, normalFont)); table.addCell(new Phrase(content1 == null ? "" : content1.replaceAll("[\r\n]", " "), normalFont)); table.addCell(new Phrase(content2 == null ? "" : content2.replaceAll("[\r\n]", " "), normalFont)); } } document.add(table); document.close(); byte[] pdfBytes = byteArrayOutputStream.toByteArray(); Files.write(Paths.get(path), pdfBytes); return f; }
From source file:net.algem.security.UserCtrl.java
License:Open Source License
private File getFollowUpAsPDF(String userId, String from, String to) throws IOException, BadElementException, DocumentException { String path = "/tmp/" + "suivi-" + userId + ".pdf"; File f = new File(path); LOGGER.log(Level.INFO, f.getName()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Document document = new Document(PageSize.A4.rotate()); PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open() document.open();// w ww. j a v a 2s . c o m PdfPTable table = new PdfPTable(10); table.setWidthPercentage(100); table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f }); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false); BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false); Font normalFont = new Font(bf, 10); Font boldFont = new Font(bfb, 10); String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE); String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE); String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " " + organization.get("name.label"); String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to; PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont)); headerCell.setBackgroundColor(Color.LIGHT_GRAY); headerCell.setColspan(10); table.addCell(headerCell); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("teacher.label", null, CTX_LOCALE), boldFont))); String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE); table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont))); fillPdfTable(table, getFollowUpSchedules(userId, from, to), normalFont); document.add(table); document.close(); byte[] pdfBytes = byteArrayOutputStream.toByteArray(); Files.write(Paths.get(path), pdfBytes); return f; }
From source file:net.bull.javamelody.internal.web.pdf.PdfDocumentFactory.java
License:Apache License
private void createWriter(Document document, String title) throws DocumentException, IOException { final PdfWriter writer = PdfWriter.getInstance(document, output); //writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft); // title/*from w w w . j a v a 2s .c om*/ final HeaderFooter header = new HeaderFooter(new Phrase(title), false); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); // simple page numbers : x //HeaderFooter footer = new HeaderFooter(new Phrase(), true); //footer.setAlignment(Element.ALIGN_RIGHT); //footer.setBorder(Rectangle.TOP); //document.setFooter(footer); // add the event handler for advanced page numbers : x/y writer.setPageEvent(new PdfAdvancedPageNumberEvents()); }
From source file:net.bull.javamelody.swing.print.MPdfWriter.java
License:Apache License
/** * We create a writer that listens to the document and directs a PDF-stream to out * * @param table/*from www . j a va 2 s . com*/ * MBasicTable * @param document * Document * @param out * OutputStream * @return DocWriter * @throws DocumentException * e */ protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out) throws DocumentException { final PdfWriter writer = PdfWriter.getInstance(document, out); // writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft); // title if (table.getName() != null) { final HeaderFooter header = new HeaderFooter(new Phrase(table.getName()), false); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); document.addTitle(table.getName()); } // simple page numbers : x // HeaderFooter footer = new HeaderFooter(new Phrase(), true); // footer.setAlignment(Element.ALIGN_RIGHT); // footer.setBorder(Rectangle.TOP); // document.setFooter(footer); // add the event handler for advanced page numbers : x/y writer.setPageEvent(new AdvancedPageNumberEvents()); return writer; }
From source file:net.filterlogic.util.imaging.ToPDF.java
License:Apache License
public static void FromTIFF(String[] files, String pdfOutFile) throws OpenCaptureImagingException { String tiff_file;// w w w. j ava 2s . c om String pdf_file = pdfOutFile; try { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file)); writer.setFullCompression(); int pages = 0; document.open(); PdfContentByte cb = writer.getDirectContent(); RandomAccessFileOrArray ra = null; for (int i = 0; i < files.length; i++) { int comps = 0; tiff_file = files[i]; try { ra = new RandomAccessFileOrArray(tiff_file); comps = TiffImage.getNumberOfPages(ra); } catch (Throwable e) { throw new Exception("Exception in " + tiff_file + " " + e.toString()); //continue; } //System.out.println("Processing: " + tiff_file); for (int c = 0; c < comps; ++c) { try { Image img = TiffImage.getTiffImage(ra, c + 1); if (img != null) { //System.out.println("page " + (c + 1)); img.scaleToFit(675, 775); img.setAbsolutePosition(0, 50); // document.add(new Paragraph(tiff_file + " - page " + (c + 1))); cb.addImage(img); document.newPage(); ++pages; } } catch (Throwable e) { throw new Exception("Exception " + tiff_file + " page " + (c + 1) + " " + e.getMessage()); } } ra.close(); } // close pdf document.close(); } catch (Exception e) { throw new OpenCaptureImagingException("ToPDF exception: " + e.toString()); } }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Writes a PDF from multiple image files to a {@link File}. * //from www. j av a2s . c om * @param pageSize * of the PDF * @param scale * images to fit the page size * @param file * output as PDF * @param files * for the PDF * @throws DocumentException * @throws IOException * @see File * @see Rectangle * @since 0.9.2 */ public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file, final File... files) throws DocumentException, IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(pageSize, scale, file, files)); if (null == pageSize) { throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$ } if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } if (null == files) { throw new RuntimeExceptionIsNull("files"); //$NON-NLS-1$ } if (!HelperArray.isValid(files)) { throw new RuntimeExceptionIsEmpty("files"); //$NON-NLS-1$ } final Document document = new Document(pageSize); document.setMargins(0.0F, 0.0F, 0.0F, 0.0F); final FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); try { PdfWriter.getInstance(document, fos); document.open(); for (final File inputFile : files) { if (null == inputFile) { throw new RuntimeExceptionIsNull("inputFile"); //$NON-NLS-1$ } final Image image = Image.getInstance(inputFile.getAbsolutePath()); if (scale) { image.scaleToFit(pageSize.getWidth(), pageSize.getHeight()); } document.add(image); document.newPage(); } } finally { document.close(); fos.close(); } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Writes a PDF from multiple {@link java.awt.Image} to a {@link File}. * // www.ja va 2 s . c o m * @param pageSize * of the PDF * @param scale * images to fit the page size * @param file * output as PDF * @param images * for the PDF * @throws DocumentException * @throws IOException * @see File * @see java.awt.Image * @see Rectangle * @since 0.9.2 */ public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file, final java.awt.Image... images) throws DocumentException, IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(pageSize, scale, file, images)); if (null == pageSize) { throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$ } if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } if (null == images) { throw new RuntimeExceptionIsNull("images"); //$NON-NLS-1$ } if (!HelperArray.isValid(images)) { throw new RuntimeExceptionIsEmpty("images"); //$NON-NLS-1$ } final Document document = new Document(pageSize); document.setMargins(0.0F, 0.0F, 0.0F, 0.0F); final FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); try { PdfWriter.getInstance(document, fos); document.open(); for (final java.awt.Image tempImage : images) { if (null == tempImage) { throw new RuntimeExceptionIsNull("tempImage"); //$NON-NLS-1$ } final Image image = Image.getInstance(tempImage, null); if (scale) { image.scaleToFit(pageSize.getWidth(), pageSize.getHeight()); } document.add(image); document.newPage(); } } finally { document.close(); fos.close(); } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }