Java Code Examples for com.itextpdf.text.Document#open()
The following examples show how to use
com.itextpdf.text.Document#open() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InterlineSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/34681893/itextsharp-extra-space-between-lines"> * iTextSharp: Extra space between lines * </a> * <p> * Indeed, the OP's {@link Phrase#setLeading(float, float)} calls are ignored. * The reason is that the op is working in text mode. Thus, he has to use * {@link ColumnText#setLeading(float, float)} instead, cf. * {@link #testLikeUser3208131Fixed()}. * </p> */ @Test public void testLikeUser3208131() throws DocumentException, FileNotFoundException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "interline-user3208131.pdf"))); document.open(); Font font = new Font(FontFamily.UNDEFINED, 4, Font.UNDEFINED, null); PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); float gutter = 15; float colwidth = (document.getPageSize().getRight() - document.getPageSize().getLeft() - gutter) / 2; float[] left = { document.getPageSize().getLeft() + 133, document.getPageSize().getTop() - 35, document.getPageSize().getLeft() + 133, document.getPageSize().getBottom() }; float[] right = { document.getPageSize().getLeft() + colwidth, document.getPageSize().getTop() - 35, document.getPageSize().getLeft() + colwidth, document.getPageSize().getBottom() }; for (int i = 0; i < 3; i++) { Phrase Ps = new Phrase("Test " + i + "\n", font); Ps.setLeading(0.0f, 0.6f); ct.addText(Ps); ct.addText(Chunk.NEWLINE); } ct.setColumns(left, right); ct.go(); document.close(); }
Example 2
Source File: TestTrimPdfPage.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
@Test public void testWithWriter() throws DocumentException, IOException { InputStream resourceStream = getClass().getResourceAsStream("test.pdf"); try { PdfReader reader = new PdfReader(resourceStream); Rectangle pageSize = reader.getPageSize(1); Rectangle rect = getOutputPageSize(pageSize, reader, 1); Document document = new Document(rect, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "test-trimmed-writer.pdf"))); document.open(); PdfImportedPage page; // Go through all pages int n = reader.getNumberOfPages(); for (int i = 1; i <= n; i++) { document.newPage(); page = writer.getImportedPage(reader, i); System.out.println("BBox: "+ page.getBoundingBox().toString()); Image instance = Image.getInstance(page); document.add(instance); Rectangle outputPageSize = document.getPageSize(); System.out.println(outputPageSize.toString()); } document.close(); } finally { if (resourceStream != null) resourceStream.close(); } }
Example 3
Source File: ColorParagraphBackground.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
@Test public void testParagraphBackgroundEventListener() throws DocumentException, FileNotFoundException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "document-with-paragraph-backgrounds.pdf"))); ParagraphBackground border = new ParagraphBackground(); writer.setPageEvent(border); document.open(); document.add(new Paragraph("Hello,")); document.add(new Paragraph("In this document, we'll add several paragraphs that will trigger page events. As long as the event isn't activated, nothing special happens, but let's make the event active and see what happens:")); border.setActive(true); document.add(new Paragraph("This paragraph now has a background. Isn't that fantastic? By changing the event, we can even draw a border, change the line width of the border and many other things. Now let's deactivate the event.")); border.setActive(false); document.add(new Paragraph("This paragraph no longer has a background.")); document.close(); }
Example 4
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createMultiUseIndirectTextPdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfReader reader = new PdfReader(createSimpleTextPdf()); PdfImportedPage template = writer.getImportedPage(reader, 1); Rectangle pageSize = reader.getPageSize(1); writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), (pageSize.getTop() + pageSize.getBottom()) / 2); writer.getDirectContent().addTemplate(template, 0, .7f, -.7f, 0, pageSize.getRight(), pageSize.getBottom()); document.newPage(); writer.getDirectContent().addTemplate(template, pageSize.getLeft(), pageSize.getBottom()); document.close(); return baos.toByteArray(); }
Example 5
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createSimpleTextPdf() throws DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); for (int i = 1; i < 20; i++) { Paragraph paragraph = new Paragraph(); for (int j = 0; j < i; j++) paragraph.add("Hello World! "); document.add(paragraph); } document.close(); return baos.toByteArray(); }
Example 6
Source File: DenseMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); for (int i = 0; i < paragraphCount; i++) { Paragraph paragraph = new Paragraph(); paragraph.add(String.format(paragraphFormat, i)); document.add(paragraph); } document.close(); return baos.toByteArray(); }
Example 7
Source File: VeryDenseMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createSimpleTextPdf(String paragraphFormat, int paragraphCount) throws DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); for (int i = 0; i < paragraphCount; i++) { Paragraph paragraph = new Paragraph(); paragraph.add(String.format(paragraphFormat, i)); document.add(paragraph); } document.close(); return baos.toByteArray(); }
Example 8
Source File: SwingExportUtil.java From mzmine3 with GNU General Public License v2.0 | 6 votes |
/** * Writes swing to pdf * * @param panel * @param fileName * @throws DocumentException * @throws Exception */ public static void writeToPDF(JComponent panel, File fileName) throws IOException, DocumentException { // print the panel to pdf int width = panel.getWidth(); int height = panel.getHeight(); logger.info( () -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}", width, height, fileName.getAbsolutePath())); Document document = new Document(new Rectangle(width, height)); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper()); panel.print(g2); g2.dispose(); contentByte.addTemplate(template, 0, 0); document.close(); writer.close(); } finally { if (document.isOpen()) { document.close(); } } }
Example 9
Source File: UseColumnText.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/32162759/columntext-showtextaligned-vs-columntext-setsimplecolumn-top-alignment"> * ColumnText.ShowTextAligned vs ColumnText.SetSimpleColumn Top Alignment * </a> * <p> * Indeed, the coordinates do not line up. The y coordinate of * {@link ColumnText#showTextAligned(PdfContentByte, int, Phrase, float, float, float)} * denotes the baseline while {@link ColumnText#setSimpleColumn(Rectangle)} surrounds * the text to come. * </p> */ @Test public void testShowTextAlignedVsSimpleColumnTopAlignment() throws DocumentException, IOException { Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "ColumnTextTopAligned.pdf"))); document.open(); Font fontQouteItems = new Font(BaseFont.createFont(), 12); PdfContentByte canvas = writer.getDirectContent(); // Item Number ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("36222-0", fontQouteItems), 60, 450, 0); // Estimated Qty ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, new Phrase("47", fontQouteItems), 143, 450, 0); // Item Description ColumnText ct = new ColumnText(canvas); // Uses a simple column box to provide proper text wrapping ct.setSimpleColumn(new Rectangle(193, 070, 390, 450)); ct.setText(new Phrase("In-Situ : Poly Cable - 100'\nPoly vented rugged black gable 100ft\nThis is an additional description. It can wrap an extra line if it needs to so this text is long.", fontQouteItems)); ct.go(); document.close(); }
Example 10
Source File: SmartMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
public static byte[] Merge(File[] documentPaths) throws IOException, DocumentException { byte[] mergedDocument; try (ByteArrayOutputStream memoryStream = new ByteArrayOutputStream()) { Document document = new Document(); PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, memoryStream); document.open(); for (File docPath : documentPaths) { PdfReader reader = new PdfReader(docPath.toString()); try { reader.consolidateNamedDestinations(); int numberOfPages = reader.getNumberOfPages(); for (int page = 0; page < numberOfPages;) { PdfImportedPage pdfImportedPage = pdfSmartCopy.getImportedPage(reader, ++page); pdfSmartCopy.addPage(pdfImportedPage); } } finally { reader.close(); } } document.close(); mergedDocument = memoryStream.toByteArray(); } return mergedDocument; }
Example 11
Source File: PdfExportTest.java From xiaoyaoji with GNU General Public License v3.0 | 5 votes |
@Test public void test() throws IOException, DocumentException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(DEST)); document.open(); putData(document); document.close(); }
Example 12
Source File: LandscapePdf.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/47209312/i-have-a-trouble-with-lowagie-pdf-and-report-making-i-cant-include-headerfooter"> * I have a trouble with lowagie pdf and Report Making. I cant include headerfooter on the first page * </a> * <p> * This example shows how to generate a PDF with page level * settings (page size, page margins) customized already on * the first page. * </p> */ @Test public void testCreateLandscapeDocument() throws FileNotFoundException, DocumentException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "landscape.pdf"))); document.setPageSize(PageSize.A4.rotate()); document.setMargins(60, 30, 30, 30); document.open(); document.add(new Paragraph("Test string for a landscape PDF.")); document.close(); }
Example 13
Source File: PdfReportBuilder.java From bdf3 with Apache License 2.0 | 5 votes |
public Document createDocument(ReportTitle reportTitle, OutputStream out) throws Exception { Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, out); if (reportTitle.isShowPageNo()) { PdfReportPageNumber event = new PdfReportPageNumber(chineseFont); writer.setPageEvent(event); } doc.open(); Paragraph paragraph = this.createReportTitle(reportTitle); doc.add(paragraph); return doc; }
Example 14
Source File: PdfExportGenerator.java From axelor-open-suite with GNU Affero General Public License v3.0 | 5 votes |
public PdfExportGenerator(AdvancedExport advancedExport) throws AxelorException { this.advancedExport = advancedExport; exportFileName = advancedExport.getMetaModel().getName() + ".pdf"; document = new Document(); table = new PdfPTable(advancedExport.getAdvancedExportLineList().size()); try { exportFile = File.createTempFile(advancedExport.getMetaModel().getName(), ".pdf"); FileOutputStream outStream = new FileOutputStream(exportFile); PdfWriter.getInstance(document, outStream); } catch (IOException | DocumentException e) { TraceBackService.trace(e); throw new AxelorException(e, TraceBackRepository.CATEGORY_CONFIGURATION_ERROR); } document.open(); }
Example 15
Source File: ImportPageWithoutFreeSpace.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/31980979/itext-importing-styled-text-and-informations-from-an-existing-pdf"> * iText: Importing styled Text and informations from an existing PDF * </a> * <p> * This method demonstrates how to import merely the region of a PDF page with * actual content. The main necessity is to call {@link #cropPdf(PdfReader)} * for the reader in question which restricts the media boxes of the pages to * the bounding box of the existing content. * </p> */ @Test public void testImportPages() throws DocumentException, IOException { byte[] docText = createSimpleTextPdf(); Files.write(new File(RESULT_FOLDER, "textOnly.pdf").toPath(), docText); byte[] docGraphics = createSimpleCircleGraphicsPdf(); Files.write(new File(RESULT_FOLDER, "graphicsOnly.pdf").toPath(), docGraphics); PdfReader readerText = new PdfReader(docText); cropPdf(readerText); PdfReader readerGraphics = new PdfReader(docGraphics); cropPdf(readerGraphics); try ( FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER, "importPages.pdf"))) { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, fos); document.open(); document.add(new Paragraph("Let's import 'textOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD))); document.add(Image.getInstance(writer.getImportedPage(readerText, 1))); document.add(new Paragraph("and now 'graphicsOnly.pdf'", new Font(FontFamily.HELVETICA, 12, Font.BOLD))); document.add(Image.getInstance(writer.getImportedPage(readerGraphics, 1))); document.add(new Paragraph("That's all, folks!", new Font(FontFamily.HELVETICA, 12, Font.BOLD))); document.close(); } finally { readerText.close(); readerGraphics.close(); } }
Example 16
Source File: PptxToPDFConverter.java From docs-to-pdf-converter with MIT License | 4 votes |
@Override public void convert() throws Exception { loading(); Dimension pgsize = processSlides(); processing(); double zoom = 2; // magnify it by 2 as typical slides are low res AffineTransform at = new AffineTransform(); at.setToScale(zoom, zoom); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outStream); document.open(); for (int i = 0; i < getNumSlides(); i++) { BufferedImage bufImg = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB); Graphics2D graphics = bufImg.createGraphics(); graphics.setTransform(at); //clear the drawing area graphics.setPaint(getSlideBGColor(i)); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); try{ drawOntoThisGraphic(i, graphics); } catch(Exception e){ //Just ignore, draw what I have } Image image = Image.getInstance(bufImg, null); document.setPageSize(new Rectangle(image.getScaledWidth(), image.getScaledHeight())); document.newPage(); image.setAbsolutePosition(0, 0); document.add(image); } //Seems like I must close document if not output stream is not complete document.close(); //Not sure what repercussions are there for closing a writer but just do it. writer.close(); finished(); }
Example 17
Source File: TestTransparency.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
@Test public void testComplex() throws FileNotFoundException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "transparencyComplex.pdf"))); writer.setCompressionLevel(0); document.open(); PdfContentByte content = writer.getDirectContent(); content.setRGBColorStroke(0, 255, 0); for (int y = 0; y <= 400; y+= 10) { content.moveTo(0, y); content.lineTo(500, y); } for (int x = 0; x <= 500; x+= 10) { content.moveTo(x, 0); content.lineTo(x, 400); } content.stroke(); PdfTemplate template = content.createTemplate(500, 400); PdfTransparencyGroup group = new PdfTransparencyGroup(); group.put(PdfName.CS, PdfName.DEVICEGRAY); group.setIsolated(false); group.setKnockout(false); template.setGroup(group); PdfShading radial = PdfShading.simpleRadial(writer, 262, 186, 10, 262, 186, 190, BaseColor.WHITE, BaseColor.BLACK, true, true); template.paintShading(radial); PdfDictionary mask = new PdfDictionary(); mask.put(PdfName.TYPE, PdfName.MASK); mask.put(PdfName.S, new PdfName("Luminosity")); mask.put(new PdfName("G"), template.getIndirectReference()); content.saveState(); PdfGState state = new PdfGState(); state.put(PdfName.SMASK, mask); content.setGState(state); content.setRGBColorFill(255, 0, 0); content.moveTo(162, 86); content.lineTo(162, 286); content.lineTo(362, 286); content.lineTo(362, 86); content.closePath(); //content.fillStroke(); content.fill(); content.restoreState(); document.close(); }
Example 18
Source File: eReceipt.java From smartcoins-wallet with MIT License | 4 votes |
private void generatePdf() { try { showProgressBar(); verifyStoragePermissions(this); final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getResources().getString(R.string.folder_name) + File.separator + "eReceipt-" + transactionId + ".pdf"; Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(path)); document.open(); Bitmap bitmap = Bitmap.createBitmap( llall.getWidth(), llall.getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bitmap); llall.draw(c); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] imageInByte = stream.toByteArray(); Image myImage = Image.getInstance(imageInByte); float documentWidth = document.getPageSize().getWidth(); float documentHeight = document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin(); myImage.scaleToFit(documentWidth, documentHeight); myImage.setAlignment(Image.ALIGN_CENTER | Image.MIDDLE); document.add(myImage); document.close(); this.runOnUiThread(new Runnable() { public void run() { Intent email = new Intent(Intent.ACTION_SEND); Uri uri = Uri.fromFile(new File(path)); email.putExtra(Intent.EXTRA_STREAM, uri); email.putExtra(Intent.EXTRA_SUBJECT, "eReceipt " + date); email.setType("application/pdf"); email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(email); } }); hideProgressBar(); } catch (Exception e) { Log.e(TAG, "Exception while tryig to share receipt info. Msg: " + e.getMessage()); } }
Example 19
Source File: AddRotatedImage.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
/** * <a href="http://stackoverflow.com/questions/39364197/how-to-rotate-around-the-image-center-by-itext"> * How to rotate around the image center by itext? * </a> * <p> * This test draws an image at given coordinates without rotation and then again * as if that image was flipped and rotated around its center by some angle. * </p> */ @Test public void testAddRotatedFlippedImage() throws IOException, DocumentException { try ( FileOutputStream stream = new FileOutputStream(new File(RESULT_FOLDER, "rotatedFlippedImage.pdf")) ) { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, stream); document.open(); PdfContentByte contentByte = writer.getDirectContent(); int x = 200; int y = 300; float rotate = (float) Math.PI / 3; try (InputStream imageStream = getClass().getResourceAsStream("/mkl/testarea/itext5/layer/Willi-1.jpg")) { Image image = Image.getInstance(IOUtils.toByteArray(imageStream)); // Draw image at x,y without rotation contentByte.addImage(image, image.getWidth(), 0, 0, image.getHeight(), x, y); // Draw image as if the previous image was flipped and rotated around its center // Image starts out being 1x1 with origin in lower left // Move origin to center of image AffineTransform A = AffineTransform.getTranslateInstance(-0.5, -0.5); // Flip it horizontally AffineTransform B = new AffineTransform(-1, 0, 0, 1, 0, 0); // Stretch it to its dimensions AffineTransform C = AffineTransform.getScaleInstance(image.getWidth(), image.getHeight()); // Rotate it AffineTransform D = AffineTransform.getRotateInstance(rotate); // Move it to have the same center as above AffineTransform E = AffineTransform.getTranslateInstance(x + image.getWidth()/2, y + image.getHeight()/2); // Concatenate AffineTransform M = (AffineTransform) A.clone(); M.preConcatenate(B); M.preConcatenate(C); M.preConcatenate(D); M.preConcatenate(E); //Draw contentByte.addImage(image, M); } document.close(); } }
Example 20
Source File: ReportFactory.java From graylog-plugin-aggregates with GNU General Public License v3.0 | 2 votes |
@SuppressWarnings("deprecation") public static void writeChartsToPDF(List<JFreeChart> charts, int width, int height, OutputStream outputStream, String hostname, Date date) { PdfWriter writer = null; Document document = new Document(); try { writer = PdfWriter.getInstance(document, outputStream); writer.setPageEmpty(false); document.open(); document.setPageSize(PageSize.A4); document.add(new Paragraph("Aggregates Report generated by " + hostname + " on " + date.toString())); document.newPage(); writer.newPage(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template; Graphics2D graphics2d; int position = 0; Rectangle2D rectangle2d; for (JFreeChart chart : charts){ LOG.debug("Writing chart to PDF"); if (writer.getVerticalPosition(true)-height+(height*position) < 0){ position = 0; document.newPage(); writer.newPage(); } template = contentByte.createTemplate(width, height); graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 38, writer.getVerticalPosition(true)-height+(height*position)); position--; } } catch (Exception e) { e.printStackTrace(); } document.close(); }