List of usage examples for com.lowagie.text Document Document
public Document()
Document
-object. From source file:de.appplant.cordova.plugin.printer.Printer.java
License:Apache License
/** * Slices the screenshot into pages, merges those into a single pdf * and saves it in the public accessible /sdcard dir. *///from w w w .j av a2 s .c o m private File saveWebViewAsPdf(Bitmap screenshot) { try { File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/"); dir.mkdirs(); File file; FileOutputStream stream; double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3) Bitmap currPage; int totalSize = screenshot.getHeight(); int currPos = 0; int currPageCount = 0; int sliceWidth = screenshot.getWidth(); int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation); while (totalSize > currPos && currPageCount < 100) // max 100 pages { currPageCount++; Log.v(LOG_TAG, "Creating page nr. " + currPageCount); // slice bitmap currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth, (int) Math.min(sliceHeight, totalSize - currPos)); // save page as png stream = new FileOutputStream(new File(dir, "print-page-" + currPageCount + ".png")); currPage.compress(Bitmap.CompressFormat.PNG, 100, stream); stream.close(); // move current position indicator currPos += sliceHeight; } // create pdf Log.v(LOG_TAG, "Creating pdf"); Document document = new Document(); File filePdf = new File(dir, this.printTitle + ".pdf"); // change the output name of the pdf here PdfWriter.getInstance(document, new FileOutputStream(filePdf)); document.open(); for (int i = 1; i <= currPageCount; ++i) { Log.v(LOG_TAG, "Adding page nr. " + i + " to the pdf file."); file = new File(dir, "print-page-" + i + ".png"); Image image = Image.getInstance(file.getAbsolutePath()); image.scaleToFit((float) pageWidth, 9999); image.setAlignment(Element.ALIGN_CENTER); document.add(image); document.newPage(); } document.close(); // delete tmp image files for (int i = 1; i <= currPageCount; ++i) { file = new File(dir, "print-page-" + i + ".png"); file.delete(); } return filePdf; } catch (IOException e) { Log.e(LOG_TAG, "ERROR: " + e.getMessage()); e.printStackTrace(); // return error answer to cordova PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); result.setKeepCallback(false); ctx.sendPluginResult(result); } catch (DocumentException e) { Log.e(LOG_TAG, "ERROR: " + e.getMessage()); e.printStackTrace(); // return error answer to cordova PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage()); result.setKeepCallback(false); ctx.sendPluginResult(result); } Log.e(LOG_TAG, "Uncaught ERROR!"); return null; }
From source file:de.chott.jfreechartsample.service.ChartService.java
/** * Schreibt mehrere JFreeCharts in ein PDF. Fr jedes Chart wird hierbei eine halbe PDF-Seite verwendet. * /*from w w w . ja v a 2s .c o m*/ * @param charts * @return Das PDF als ByteArray */ private byte[] writeChartsToDocument(JFreeChart... charts) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); float width = PageSize.A4.getWidth(); float height = PageSize.A4.getHeight() / 2; int index = 0; Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte contentByte = writer.getDirectContent(); for (JFreeChart chart : charts) { PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2D = template.createGraphics(width, height); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2D, rectangle2D); graphics2D.dispose(); contentByte.addTemplate(template, 0, height - (height * index)); index++; } writer.flush(); document.close(); return baos.toByteArray(); } catch (Exception ex) { Logger.getLogger(ChartService.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:de.cuseb.bilderbuch.pdf.PdfController.java
License:Open Source License
@RequestMapping(value = "/pdf", method = RequestMethod.GET) public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) { try {//from ww w. java 2 s .c om PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest"); httpServletResponse.setContentType("application/pdf"); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream()); writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB); //document.addAuthor(pdfRequest.getAuthor()); //document.addTitle(pdfRequest.getTitle()); document.setPageSize( new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148))); document.open(); FontFactory.defaultEmbedding = true; FontFactory.register("IndieRock.ttf", "IndieRock"); Font font = FontFactory.getFont("IndieRock"); BaseFont baseFont = font.getBaseFont(); PdfContentByte cb = writer.getDirectContent(); Iterator<PdfPage> pages = pdfRequest.getPages().iterator(); while (pages.hasNext()) { PdfPage page = pages.next(); if (page.getImage() != null) { Image image = Image.getInstance(new URL(page.getImage().getUrl())); image.setDpi(300, 300); image.setAbsolutePosition(0f, 0f); image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight()); document.add(image); cb.saveState(); cb.beginText(); cb.setColorFill(Color.WHITE); cb.moveText(10f, 10f); cb.setFontAndSize(baseFont, 18); cb.showText(page.getSentence()); cb.endText(); cb.restoreState(); if (pages.hasNext()) { document.newPage(); } } } document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:de.d3web.empiricaltesting.casevisualization.jung.JUNGCaseVisualizer.java
License:Open Source License
/** * Streams the graph to an OutputStream (useful for web requests!) * //w ww .j a va 2 s.c o m * @param cases List<SequentialTestCase> cases * @param outStream OutputStream */ @Override public void writeToStream(java.util.List<SequentialTestCase> cases, java.io.OutputStream outStream) throws IOException { init(cases); int w = vv.getGraphLayout().getSize().width; int h = vv.getGraphLayout().getSize().height; Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, outStream); document.setPageSize(new Rectangle(w, h)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2 = tp.createGraphics(w, h); paintGraph(g2); g2.dispose(); tp.sanityCheck(); cb.addTemplate(tp, 0, 0); cb.sanityCheck(); document.close(); } catch (DocumentException e) { throw new IOException("Error while writing to file. The file was not created. ", e); } }
From source file:de.dhbw.humbuch.util.PDFHandler.java
/** * /*from w w w. j ava2 s. c om*/ * @param path * links to the directory where the PDF file should be saved */ public PDFHandler(String path) { this.document = new Document(); }
From source file:de.intranda.test_ics.ImageHelper.java
License:Apache License
public void doGeneration(File[] imageFiles, File pdfFile) throws IOException, DocumentException, OutOfMemoryError { if (imageFiles.length > 0) { // allImages = reverseFileList(allImages); Document pdfDocument = null; @SuppressWarnings("unused") int pageCount = 1; PdfWriter pdfWriter = null;//from www . j a va 2s . com pdfDocument = new Document(); FileOutputStream outputPdfFile = new FileOutputStream(pdfFile); pdfWriter = PdfWriter.getInstance(pdfDocument, outputPdfFile); pdfDocument.open(); for (File imageFile : imageFiles) { addPage(imageFile, pdfWriter, pdfDocument, 1, 0); pageCount++; } pdfDocument.close(); pdfWriter.close(); try { if (outputPdfFile != null) { outputPdfFile.close(); } } catch (IOException e) { LOGGER.warn("Error on closing fileoutputstream"); } } }
From source file:de.ipbhalle.metfrag.tools.renderer.WritePDFTable.java
License:Open Source License
/** * Instantiates a new write pdf table. This is mainly for debugging the gasteiger marsili charges * /*from w w w. j a va 2s. c om*/ * @param odir the odir * @param width the width * @param height the height * @param chargeResults the charge results */ public WritePDFTable(String odir, int width, int height, List<ChargeResult> chargeResults) { this.width = width; this.height = height; try { File file = new File(odir); document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); float[] widths = new float[ncol]; for (int i = 0; i < ncol; i += 3) { widths[i] = 2.5f; widths[i + 1] = 0.75f; widths[i + 2] = 0.75f; } table = new PdfPTable(widths); document.open(); boolean drawPartialCharges = true; for (ChargeResult result : chargeResults) { if (drawPartialCharges) { PdfPCell cellBonds = new PdfPCell(); PdfPCell cellBondsDist = new PdfPCell(); Phrase phraseBonds = new Phrase(); Phrase phraseBondsDist = new Phrase(); com.lowagie.text.Image image = com.lowagie.text.Image .getInstance(writeMOL2PNGFile(result.getOriginalMol()).getAbsolutePath()); image.setAbsolutePosition(0, 0); table.addCell(image); String stringAtoms = ""; String stringAtomsCharge = ""; for (IAtom atom : result.getOriginalMol().atoms()) { if (!atom.getSymbol().equals("H") && !atom.getSymbol().equals("C")) { stringAtoms += atom.getSymbol() + (Integer.parseInt(atom.getID()) + 1) + "\n"; stringAtomsCharge += Math.round(atom.getCharge() * 100.0) / 100.0 + "\n"; } } addProperty(phraseBonds, stringAtoms); addProperty(phraseBondsDist, stringAtomsCharge); cellBonds.addElement(phraseBonds); cellBondsDist.addElement(phraseBondsDist); table.addCell(cellBonds); table.addCell(cellBondsDist); drawPartialCharges = false; } PdfPCell cellBonds = new PdfPCell(); PdfPCell cellBondsDist = new PdfPCell(); Phrase phraseBonds = new Phrase(); Phrase phraseBondsDist = new Phrase(); com.lowagie.text.Image image = com.lowagie.text.Image.getInstance( writeMOL2PNGFile(result.getOriginalMol(), result.getMolWithProton()).getAbsolutePath()); image.setAbsolutePosition(0, 0); table.addCell(image); String stringPDFBonds = ""; String stringPDFBondsDist = ""; String[] lines = result.getChargeString().split("\n"); for (int i = 0; i < lines.length; i++) { boolean carbonHydrogenBond = lines[i].matches("[A-Z]+[0-9]+-H[0-9]+.*"); if (!carbonHydrogenBond) { String[] linesArr = lines[i].split("\t"); stringPDFBondsDist += linesArr[1] + "\n"; stringPDFBonds += linesArr[0] + "\n"; } } addProperty(phraseBonds, stringPDFBonds); addProperty(phraseBondsDist, stringPDFBondsDist); cellBonds.addElement(phraseBonds); cellBondsDist.addElement(phraseBondsDist); table.addCell(cellBonds); table.addCell(cellBondsDist); } document.add(table); document.close(); } catch (Exception exc) { exc.printStackTrace(); } }
From source file:de.japes.text.PdfCreator.java
License:Open Source License
public String exportToPdf(byte[] imgArray) { String filename;/*from w w w . j a va 2 s . c om*/ Document document = new Document(); Image img = null; Calendar cal = Calendar.getInstance(); filename = "chart_" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) + ".pdf"; try { img = Image.getInstance(imgArray); } catch (MalformedURLException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } catch (BadElementException e) { return e.getMessage(); } img.setAlignment(Image.ALIGN_CENTER); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document document.add(img); } catch (DocumentException de) { return de.getMessage(); } catch (IOException ioe) { return ioe.getMessage(); } // step 5: we close the document document.close(); return filename; }
From source file:de.offis.health.icardea.cied.pdf.extractor.PDFiText2Extractor.java
License:LGPL
public byte[] getPDFPages(int fromPageNumber, int toPageNumber) { ByteArrayOutputStream byteArrayOutputStream = null; boolean extractionSuccessful = false; if (pdfReader != null) { int numberOfPages = getNumberOfPages(); /*/*from w w w.j ava 2s . c o m*/ * Check if the given page numbers are in the allowed range. */ if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0 && toPageNumber <= numberOfPages) { /* * Now check if the given fromPageNumber is smaller * as the given toPageNumber. If not swap the numbers. */ if (fromPageNumber > toPageNumber) { int tmpPageNumber = toPageNumber; toPageNumber = fromPageNumber; fromPageNumber = tmpPageNumber; } Document newDocument = new Document(); try { byteArrayOutputStream = new ByteArrayOutputStream(); PdfSmartCopy pdfCopy = new PdfSmartCopy(newDocument, byteArrayOutputStream); newDocument.open(); for (int currentPage = fromPageNumber; currentPage <= toPageNumber; currentPage++) { pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, currentPage)); } // end for pdfCopy.flush(); pdfCopy.close(); newDocument.close(); extractionSuccessful = true; } catch (DocumentException ex) { // TODO: Create an own exception for PDF processing errors. logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex); } catch (IOException ex) { // TODO: Create an own exception for PDF processing errors. logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex); } finally { if (!extractionSuccessful) { byteArrayOutputStream = null; } } // end try..catch..finally } // end if checking range of given pages } // end if (pdfReader != null) if (byteArrayOutputStream != null) { return byteArrayOutputStream.toByteArray(); } return null; }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
License:Open Source License
/** * Generate result as PDF.//w w w.ja v a 2 s . c o m */ public void generateResultAsPdf() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { /* * Vorbereiten der Header-Informationen */ HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); try { ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType("search.pdf"); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\""); ServletOutputStream out = response.getOutputStream(); SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses, this.showArchivedProjects); HSSFWorkbook wb = sr.getResult(); List<List<HSSFCell>> rowList = new ArrayList<>(); HSSFSheet mySheet = wb.getSheetAt(0); Iterator<Row> rowIter = mySheet.rowIterator(); while (rowIter.hasNext()) { HSSFRow myRow = (HSSFRow) rowIter.next(); Iterator<Cell> cellIter = myRow.cellIterator(); List<HSSFCell> row = new ArrayList<>(); while (cellIter.hasNext()) { HSSFCell myCell = (HSSFCell) cellIter.next(); row.add(myCell); } rowList.add(row); } Document document = new Document(); Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth()); PdfWriter.getInstance(document, out); document.setPageSize(a4quer); document.open(); if (rowList.size() > 0) { Paragraph p = new Paragraph(rowList.get(0).get(0).toString()); document.add(p); PdfPTable table = new PdfPTable(9); table.setSpacingBefore(20); for (List<HSSFCell> row : rowList) { for (HSSFCell hssfCell : row) { // TODO aufhbschen und nicht toString() nutzen String stringCellValue = hssfCell.toString(); table.addCell(stringCellValue); } } document.add(table); } document.close(); out.flush(); facesContext.responseComplete(); } catch (Exception e) { logger.error(e); } } }