Java Code Examples for com.itextpdf.text.pdf.PdfWriter#getInstance()
The following examples show how to use
com.itextpdf.text.pdf.PdfWriter#getInstance() .
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: PDFExport.java From MtgDesktopCompanion with GNU General Public License v3.0 | 8 votes |
@Override public void exportDeck(MagicDeck deck, File f) throws IOException { PdfPTable table = new PdfPTable(3); table.setHorizontalAlignment(Element.ALIGN_CENTER); try { document = new Document(PageSize.A4, 5, 5, 10, 5); document.addAuthor(getString("AUTHOR")); document.addCreationDate(); document.addCreator(MTGConstants.MTG_APP_NAME); document.addTitle(deck.getName()); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f)); document.open(); document.add(new Chunk("")); for (MagicCard card : deck.getMainAsList()) { table.addCell(getCells(card)); notify(card); } document.add(table); document.close(); writer.close(); } catch (Exception e) { logger.error("Error in pdf creation " + f, e); } }
Example 2
Source File: VeryDenseMerging.java From testarea-itext5 with GNU Affero General Public License v3.0 | 8 votes |
static byte[] createSimpleCircleGraphicsPdf(int radius, int gap, int count) throws DocumentException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); float y = writer.getPageSize().getTop(); for (int i = 0; i < count; i++) { Rectangle pageSize = writer.getPageSize(); if (y <= pageSize.getBottom() + 2*radius) { y = pageSize.getTop(); writer.getDirectContent().fillStroke(); document.newPage(); } writer.getDirectContent().circle(pageSize.getLeft() + pageSize.getWidth() * Math.random(), y-radius, radius); y-= 2*radius + gap; } writer.getDirectContent().fillStroke(); document.close(); return baos.toByteArray(); }
Example 3
Source File: CreatePdf.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/41743574/itextpdf-creates-unvalid-pdf-document"> * Itextpdf creates unvalid pdf document * </a> * <p> * CasperSlynge.html * </p> * <p> * Works for me. Admittedly, I replaced the {@link ByteArrayInputStream} by a * resource {@link InputStream} and the {@link ByteArrayOutputStream} by a * {@link FileOutputStream}. * </p> * <p> * I also added a `Charset` but the test created a valid file without, too. * </p> */ @Test public void testCreatePdfLikeCasperSlynge() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("CasperSlynge.html"); FileOutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "CasperSlynge.pdf"))) { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, result); // step 3 document.open(); // step 4 XMLWorkerHelper.getInstance().parseXHtml(writer, document, resource, Charset.forName("UTF8")); // step 5 document.close(); } }
Example 4
Source File: EnlargePagePart.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/35374110/how-do-i-use-itext-to-have-a-landscaped-pdf-on-half-of-a-a4-back-to-portrait-and"> * How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4 * </a> * <p> * This sample shows how to rotate and enlarge the upper half of an A4 page to fit into a new A4 page. * </p> */ @Test public void testRotateAndZoomUpperHalfPage() throws IOException, DocumentException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/test.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "test-upperHalf.pdf")) ) { PdfReader reader = new PdfReader(resource); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(document, result); document.open(); double sqrt2 = Math.sqrt(2); Rectangle pageSize = reader.getPageSize(1); PdfImportedPage importedPage = writer.getImportedPage(reader, 1); writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2); document.close(); } }
Example 5
Source File: MemoryConsumption.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/38989235/itext-html-to-pdf-memory-leak"> * IText HTML to PDF memory leak * </a> * <p> * The OP's code plus a save-to-file. * </p> */ public void testDevelofersScenario(String outputName) throws IOException, DocumentException { final String content = "<!--?xml version=\"1.0\" encoding=\"UTF-8\"?-->\n<html>\n <head>\n <title>Title</title>\n \n \n </head>\n" + "\n \n<body> \n \n \nEXAMPLE\n\n</body>\n</html>"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); InputStream is = new ByteArrayInputStream(content.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(writer, document, is); document.close(); baos.writeTo(new FileOutputStream(new File(RESULT_FOLDER, outputName))); }
Example 6
Source File: SimpleRedactionTest.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
static byte[] createMultiUseImagePdf() throws DocumentException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter.getInstance(document, baos); document.open(); BufferedImage bim = new BufferedImage(500, 250, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bim.createGraphics(); g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, 250, 250); g2d.dispose(); Image image = Image.getInstance(bim, null); document.add(image); document.add(image); document.add(image); document.close(); return baos.toByteArray(); }
Example 7
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 8
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 9
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 10
Source File: PdfDenseMergeTool.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
void openDocument(OutputStream outputStream) throws DocumentException { final Document document = new Document(pageSize, 36, 36, topMargin, bottomMargin); final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); this.document = document; this.writer = writer; newPage(); }
Example 11
Source File: SwingExportUtil.java From mzmine2 with GNU General Public License v2.0 | 5 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 12
Source File: ChartExportUtil.java From old-mzmine3 with GNU General Public License v2.0 | 5 votes |
/** * This method saves a chart as a PDF with given dimensions * * @param chart * @param width * @param height * @param fileName is a full path */ public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName) throws Exception { PdfWriter writer = null; Document document = new Document(new Rectangle(width, height)); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); throw e; } finally { document.close(); } }
Example 13
Source File: ChartExportUtil.java From mzmine2 with GNU General Public License v2.0 | 5 votes |
/** * This method saves a chart as a PDF with given dimensions * * @param chart * @param width * @param height * @param fileName is a full path */ public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName) throws Exception { PdfWriter writer = null; Document document = new Document(new Rectangle(width, height)); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); throw e; } finally { document.close(); } }
Example 14
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 15
Source File: PDFDocument.java From tuxguitar with GNU Lesser General Public License v2.1 | 5 votes |
public void start() { try { this.document = new Document(new Rectangle(this.size.getWidth(), this.size.getHeight()) ); PdfWriter writer = PdfWriter.getInstance(this.document, this.stream); this.document.open(); this.cb = writer.getDirectContent(); } catch(Throwable e){ TGErrorManager.getInstance(this.context).handleError(e); } }
Example 16
Source File: DynamicFooter.java From testarea-itext5 with GNU Affero General Public License v3.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/43610868/how-to-add-dynamic-variable-to-footer-without-calling-document-newpage-in-itex"> * How to add dynamic variable to footer without calling document.newPage() in iText 5 * </a> * <p> * generator method of the OP * </p> * @see #testDynamicFooterLikeAyZagen() */ public static void createPdf(ArrayList<String> htmlStrings, FooterTable footerEvt, String destinationPath) throws IOException, DocumentException { Document document = new Document(PageSize.A4); document.setMargins(68, 85, 75, 85); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destinationPath)); if (footerEvt != null) writer.setPageEvent(footerEvt); document.open(); CSSResolver cssResolver = new StyleAttrCSSResolver(); CssFile cssFile = XMLWorkerHelper .getCSS(new ByteArrayInputStream(/*readCSS("resources/content.min.css").getBytes()*/ "".getBytes())); cssResolver.addCss(cssFile); XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); fontProvider.register(/*"resources/ARIAL.TTF"*/ "c:/Windows/Fonts/arial.ttf"); CssAppliers cssAppliers = new CssAppliersImpl(fontProvider); HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer); HtmlPipeline html = new HtmlPipeline(htmlContext, pdf); CssResolverPipeline css = new CssResolverPipeline(cssResolver, html); XMLWorker worker = new XMLWorker(css, true); XMLParser p = new XMLParser(worker); int i = 0; for (String htmlfile : htmlStrings) { i++; footerEvt.setTitleIndex("" + i);//or FooterTable.setTitleIndex("" + i); ByteArrayInputStream stream = new ByteArrayInputStream(htmlfile.getBytes("UTF-8")); p.parse(stream, Charset.forName("UTF-8")); } document.close(); }
Example 17
Source File: Metodos.java From ExamplesAndroid with Apache License 2.0 | 4 votes |
public void GeneratePDF() { Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/sdcard/TutorialesHackro/hoja.pdf")); document.open(); PdfPTable table = new PdfPTable(3); // 3 columns. table.setWidthPercentage(100); //Width 100% table.setSpacingBefore(10f); //Space before table table.setSpacingAfter(10f); //Space after table //Set Column widths float[] columnWidths = {1f, 1f, 1f}; table.setWidths(columnWidths); PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1")); cell1.setBorderColor(BaseColor.BLUE); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2")); cell2.setBorderColor(BaseColor.GREEN); cell2.setPaddingLeft(10); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3")); cell3.setBorderColor(BaseColor.RED); cell3.setPaddingLeft(10); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); //To avoid having the cell border and the content overlap, if you are having thick cell borders //cell1.setUserBorderPadding(true); //cell2.setUserBorderPadding(true); //cell3.setUserBorderPadding(true); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); document.add(table); createDirectoryAndSaveFile(writer, "david"); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); Log.e("ewdfhyfafedyatfawytedfytew b",e.getMessage()); } }
Example 18
Source File: Abstract2DPdfPageSplittingTool.java From testarea-itext5 with GNU Affero General Public License v3.0 | 4 votes |
void initDocument(OutputStream outputStream) throws DocumentException { final Document document = new Document(PageSize.A4); final PdfWriter writer = PdfWriter.getInstance(document, outputStream); this.document = document; this.writer = writer; }
Example 19
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 20
Source File: DrawGradient.java From testarea-itext5 with GNU Affero General Public License v3.0 | 3 votes |
/** * <a href="http://stackoverflow.com/questions/39072316/itext-gradient-issue-in-landscape"> * iText gradient issue in landscape * </a> * <p> * The problem is that while itext content adding functionalities <b>do</b> take the page * rotation into account (they translate the given coordinates so that in the rotated page * <em>x</em> goes right and <em>y</em> goes up and the origin is in the lower left), the * shading pattern definitions (which are <em>not</em> part of the page content but * externally defined) <b>don't</b>. * </p> * <p> * Thus, you have to make the shading definition rotation aware, e.g. like this. * </p> */ @Test public void testGradientOnRotatedPage() throws FileNotFoundException, DocumentException { Document doc = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(RESULT_FOLDER, "gradientProblem.pdf"))); doc.open(); drawSexyTriangle(writer, false); doc.setPageSize(PageSize.A4.rotate()); doc.newPage(); drawSexyTriangle(writer, true); doc.close(); }