private void exportGraphToPdf(mxGraph graph, String filename) { Rectangle bounds = new Rectangle(trackScheme.getGUI().graphComponent.getViewport().getViewSize()); // step 1 com.itextpdf.text.Rectangle pageSize = new com.itextpdf.text.Rectangle(bounds.x, bounds.y, bounds.width, bounds.height); com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize); // step 2 PdfWriter writer = null; Graphics2D g2 = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfContentByte canvas = writer.getDirectContent(); g2 = canvas.createGraphics(pageSize.getWidth(), pageSize.getHeight()); trackScheme.getGUI().graphComponent.getViewport().paintComponents(g2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } finally { g2.dispose(); document.close(); } }
/** * Creates a PDF document. * * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws IOException, DocumentException { // step 1 Rectangle rect = new Rectangle(-595, -842, 595, 842); Document document = new Document(rect); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 // draw the coordinate system PdfContentByte canvas = writer.getDirectContent(); canvas.moveTo(-595, 0); canvas.lineTo(595, 0); canvas.moveTo(0, -842); canvas.lineTo(0, 842); canvas.stroke(); // read the PDF with the logo PdfReader reader = new PdfReader(RESOURCE); PdfTemplate template = writer.getImportedPage(reader, 1); // add it at different positions using different transformations canvas.addTemplate(template, 0, 0); canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0); canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f); canvas.addTemplate(template, 1, 0, 0.4f, 1, -750, -650); canvas.addTemplate(template, 0, -1, -1, 0, 650, 0); canvas.addTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0); // step 5 document.close(); reader.close(); }
/** * Method to export charts as PDF files using the defined path. * * @param path The filename and absolute path. * @param chart The JFreeChart object. * @param width The width of the PDF file. * @param height The height of the PDF file. * @param mapper The font mapper for the PDF file. * @param title The title of the PDF file. * @throws IOException If writing a PDF file fails. */ @SuppressWarnings("deprecation") public static void exportPdf( String path, JFreeChart chart, int width, int height, FontMapper mapper, String title) throws IOException { File file = new File(path); FileOutputStream pdfStream = new FileOutputStream(file); BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream); Rectangle pagesize = new Rectangle(width, height); Document document = new Document(); document.setPageSize(pagesize); document.setMargins(50, 50, 50, 50); document.addAuthor("OMSimulationTool"); document.addSubject(title); try { PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput); document.open(); PdfContentByte contentByte = pdfWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D g2D = template.createGraphics(width, height, mapper); Double r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2D, r2D); g2D.dispose(); contentByte.addTemplate(template, 0, 0); } catch (DocumentException de) { JOptionPane.showMessageDialog( null, "Failed to write PDF document.\n" + de.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); de.printStackTrace(); } document.close(); }
public byte[] generaArcSol( final List<VUSolicitud> listSolic, final String titulo, final String firmaDigital) throws VUException { final Document document = new Document(PageSize.A4, 10, 10, 10, 70); final ByteArrayOutputStream bOutput = new ByteArrayOutputStream(); try { final PdfWriter writer = PdfWriter.getInstance(document, bOutput); final HeaderFooter event = new HeaderFooter(this.footer(), filesBean.getFileSctImg().getURL().getPath(), titulo); writer.setPageEvent(event); document.open(); document.add(new Paragraph(" ")); document.add(this.cuerpoSol(listSolic)); final PdfPTable tabPDF = getTablaPDF(firmaDigital); document.add(tabPDF); } catch (Exception expo) { LOGVU.error("ERRROR al generar PDF", expo); } finally { if (null != document) { document.close(); } } return bOutput.toByteArray(); }
// ---------------- for footer and header....------------------ @Override public void onEndPage(PdfWriter writer, Document document) { try { Rectangle page = document.getPageSize(); // we will print the header using the code below PdfPTable headTable = getHeader(); headTable.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); // the table is printed at the spcific location headTable.writeSelectedRows(0, -1, document.leftMargin(), 830, writer.getDirectContent()); // we will print the footer using the code below PdfPTable footTable = getFooter(); footTable.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); footTable.writeSelectedRows( 0, -1, document.leftMargin(), document.bottomMargin() - 560, writer.getDirectContent()); } catch (Exception ex) { ex.printStackTrace(); } // TODO Auto-generated method stub }
private static void booklet(String input) throws Exception { String output = input.replace(".pdf", "-booklet.pdf"); PdfReader reader = new PdfReader(input); int n = reader.getNumberOfPages(); Rectangle pageSize = reader.getPageSize(1); System.out.println("Input page size: " + pageSize); Document doc = new Document(PageSize.A4.rotate(), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output)); doc.open(); splitLine(doc, writer); int[] pages = new int[(n + 3) / 4 * 4]; int x = 1, y = pages.length; for (int i = 0; i < pages.length; ) { pages[i++] = y--; pages[i++] = x++; pages[i++] = x++; pages[i++] = y--; } PdfContentByte cb = writer.getDirectContent(); float bottom = (doc.top() - pageSize.getHeight()) / 2 + kOffset; float left = doc.right() / 2 - (pageSize.getWidth() + kTextWidth) / 2 - kMargin; float right = doc.right() / 2 - (pageSize.getWidth() - kTextWidth) / 2 + kMargin; for (int i = 0; i < pages.length; ) { PdfImportedPage page = getPage(writer, reader, pages[i++]); if (page != null) cb.addTemplate(page, left, bottom); page = getPage(writer, reader, pages[i++]); if (page != null) cb.addTemplate(page, right, bottom); doc.newPage(); } doc.close(); }
public static void main(String[] args) throws IOException, DocumentException { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontFamily = ge.getAvailableFontFamilyNames(); PrintStream out1 = new PrintStream(new FileOutputStream(RESULT1)); for (int i = 0; i < fontFamily.length; i++) { out1.println(fontFamily[i]); } out1.flush(); out1.close(); DefaultFontMapper mapper = new DefaultFontMapper(); mapper.insertDirectory("c:/windows/fonts/"); PrintStream out2 = new PrintStream(new FileOutputStream(RESULT2)); for (Entry<String, BaseFontParameters> entry : mapper.getMapper().entrySet()) { out2.println(String.format("%s: %s", entry.getKey(), entry.getValue().fontName)); } out2.flush(); out2.close(); float width = 150; float height = 150; Document document = new Document(new Rectangle(width, height)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT3)); document.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D g2d = cb.createGraphics(width, height, mapper); for (int i = 0; i < FONTS.length; ) { g2d.setFont(FONTS[i++]); g2d.drawString("Hello world", 5, 24 * i); } g2d.dispose(); document.close(); }
/** * Creates a PDF document. * * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException */ public void createPdf(String filename) throws IOException, DocumentException { // step 1 Document document = new Document(new Rectangle(360, 360)); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); writer.addJavaScript(Utilities.readFileToString(RESOURCE)); // step 4 // add the keys for the digits for (int i = 0; i < 10; i++) { addPushButton(writer, digits[i], String.valueOf(i), "this.augment(" + i + ")"); } // add the keys for the operators addPushButton(writer, plus, "+", "this.register('+')"); addPushButton(writer, minus, "-", "this.register('-')"); addPushButton(writer, mult, "x", "this.register('*')"); addPushButton(writer, div, ":", "this.register('/')"); addPushButton(writer, equals, "=", "this.calculateResult()"); // add the other keys addPushButton(writer, clearEntry, "CE", "this.reset(false)"); addPushButton(writer, clear, "C", "this.reset(true)"); addTextField(writer, result, "result"); addTextField(writer, move, "move"); // step 5 document.close(); }
public void print(String filename) throws IOException, DocumentException { EventTree tree = app.getTimelines().getCurrentTree(); if (tree == null || tree.isEmpty()) return; ComplexEvent parent = tree.getTopSelectionParent(); if (parent == null) return; // Instantiation of document object Document document = new Document(PageSize.A4, 50, 50, 50, 50); // Creation of PdfWriter object PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); // Creation of table Paragraph title = new Paragraph( "A sample output from Zeitline:", FontFactory.getFont(FontFactory.TIMES_BOLD, 14, BaseColor.BLUE)); title.setSpacingAfter(20); document.add(title); // Setting width rations PdfPTable table = new PdfPTable(3); float[] tableWidth = {(float) 0.2, (float) 0.12, (float) 0.68}; table.setWidths(tableWidth); // Setting the header java.util.List<PdfPCell> headerCells = asList(getHeaderCell("Date"), getHeaderCell("MACB"), getHeaderCell("Short Description")); for (PdfPCell cell : headerCells) table.addCell(cell); // Setting the body int max = parent.countChildren(); for (int i = 0; i < max; i++) { AbstractTimeEvent entry = parent.getEventByIndex(i); table.addCell(getBodyCell(entry.getStartTime().toString())); String name = entry.getName(); if (name != null && name.length() > 5) { String macb = name.substring(0, 4); String desc = name.substring(5); table.addCell(getBodyCell(macb)); table.addCell(getBodyCell(desc)); } else { table.addCell(""); table.addCell(""); } } document.add(table); // Closure document.close(); writer.close(); }
@Override protected void buildPdfDocument( Map<String, Object> model, Document doc, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub @SuppressWarnings("unchecked") ArrayList<ctUsuario> listaUsuario = (ArrayList<ctUsuario>) model.get("listaUsuario"); // grupo = (String)model.get("grupo"); PdfPTable tablaPDF = new PdfPTable(11); // 11 columns. Font fuenteTabla = new Font(Font.FontFamily.UNDEFINED, 12, Font.BOLD); Font fuenteCelda = new Font(Font.FontFamily.UNDEFINED, 11); tablaPDF.addCell(new Phrase("Nombre", fuenteTabla)); tablaPDF.addCell(new Phrase("Apellido", fuenteTabla)); tablaPDF.addCell(new Phrase("Fecha De Nacimiento", fuenteTabla)); tablaPDF.addCell(new Phrase("Calle", fuenteTabla)); tablaPDF.addCell(new Phrase("Num. Ext", fuenteTabla)); tablaPDF.addCell(new Phrase("Num. Int", fuenteTabla)); tablaPDF.addCell(new Phrase("Colonia", fuenteTabla)); tablaPDF.addCell(new Phrase("CP", fuenteTabla)); tablaPDF.addCell(new Phrase("Municipio", fuenteTabla)); tablaPDF.addCell(new Phrase("Estado", fuenteTabla)); tablaPDF.addCell(new Phrase("Telefono", fuenteTabla)); for (ctUsuario ctUsuario : listaUsuario) { tablaPDF.addCell(new Phrase(ctUsuario.getcNombre(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getcApellidos(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getDtFechaNac(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getcCalle(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getcNumExterior(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getcNumInterior(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getcColonia(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getcCP(), fuenteCelda)); // tablaPDF.addCell(new Phrase(ctUsuario.getcMunicipio(), fuenteCelda)); tablaPDF.addCell(new Phrase(ctUsuario.getcEstado(), fuenteCelda)); // tablaPDF.addCell(new Phrase(ctUsuario.getcTel(), fuenteCelda)); } tablaPDF.setWidthPercentage(100); Rectangle rect = new Rectangle(60, 30, 600, 800); writer.setBoxSize("art", rect); HeaderFooterPageEvent event = new HeaderFooterPageEvent(); writer.setPageEvent(event); doc.setPageSize(PageSize.A4.rotate()); doc.open(); doc.add(tablaPDF); doc.close(); pages = 0; }
/** * @param file * @param txId * @throws DocumentException * @throws IOException */ public void generatePdf(String file, ArrayList<String> docList) throws DocumentException, IOException { // getReqdInfo(txId); document = new Document(PageSize.A4, 50, 50, 100, 650); writer = PdfWriter.getInstance(document, new FileOutputStream(file)); writer.setPageEvent(agreementPdf); document.open(); getTransactionHeader(docList); document.close(); }
private static void imageToPDF(String folder, Collection<Path> all) { for (Path path : all) { Document document = new Document(); String absolutePathInput = path.toFile().getAbsolutePath(); String absolutePathOutput = folder + "/" + path.getFileName() + ".pdf"; if (absolutePathInput.endsWith(".gif") || // absolutePathInput.endsWith(".GIF") || // absolutePathInput.endsWith(".jpg") || // absolutePathInput.endsWith(".JPG") || // absolutePathInput.endsWith(".png") || // absolutePathInput.endsWith(".PNG")) { try { FileOutputStream fos = new FileOutputStream(absolutePathOutput); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); int indentation = 0; Image image = Image.getInstance(absolutePathInput); float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin() - indentation) / image.getWidth()) * 100; image.scalePercent(scaler); document.add(image); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } } }
public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); // ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, new // Phrase(grupo), rect.getRight(), rect.getBottom(), 0); ColumnText.showTextAligned( writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Pagina " + pages), rect.getLeft(), rect.getBottom(), 0); }
public void cellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases) { final PdfWriter writer = canvases[0].getPdfWriter(); final TextField textField = new TextField(writer, rectangle, fieldname); try { final PdfFormField field = textField.getTextField(); writer.addAnnotation(field); } catch (final IOException ioe) { throw new ExceptionConverter(ioe); } catch (final DocumentException de) { throw new ExceptionConverter(de); } }
public boolean convertToPDF() throws MalformedURLException, IOException { JFileChooser filechooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(".pdf", "pdf"); filechooser.setFileFilter(filter); int result = filechooser.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File saveFile = filechooser.getSelectedFile(); Document pdfDocument = new Document(); PdfPTable table = new PdfPTable(1); com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(780, 580); Image slideImage = null; PdfWriter pdfWriter; try { pdfWriter = PdfWriter.getInstance( pdfDocument, new FileOutputStream(saveFile.getAbsolutePath() + ".pdf")); pdfWriter.open(); pdfDocument.open(); // pdfDocument.setPageSize(r); for (int i = 0; i < canvas.length; i++) { BufferedImage tempimg = new BufferedImage(720, 540, BufferedImage.TYPE_INT_ARGB); Graphics2D temgraphics = (Graphics2D) tempimg.getGraphics(); temgraphics.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); temgraphics.drawImage(img[i], 0, 0, 720, 540, null); temgraphics.drawImage(canvas[i], 0, 0, 720, 540, null); // slideImage = Image.getInstance(img[i], null); slideImage = com.itextpdf.text.Image.getInstance(tempimg, null); // table.addCell(new PdfPCell(slideImage, true)); // Image imagex = com.itextpdf.text.Image.getInstance(""); pdfDocument.setPageSize(r); pdfDocument.newPage(); pdfDocument.add(slideImage); } pdfDocument.close(); pdfWriter.close(); System.out.println("Powerpoint file converted to PDF successfully"); return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { return false; } return false; }
/** * Main method. * * @param args no arguments needed * @throws DocumentException * @throws IOException */ public static void main(String[] args) throws IOException, DocumentException { // step 1 Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT)); // step 3 document.open(); // step 4 // Create and add a Paragraph Paragraph p = new Paragraph("Foobar Film Festival", new Font(FontFamily.HELVETICA, 22)); p.setAlignment(Element.ALIGN_CENTER); document.add(p); // Create and add an Image Image img = Image.getInstance(RESOURCE); img.setAbsolutePosition( (PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2, (PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2); document.add(img); // Now we go to the next page document.newPage(); document.add(p); document.add(img); // Add text on top of the image PdfContentByte over = writer.getDirectContent(); over.saveState(); float sinus = (float) Math.sin(Math.PI / 60); float cosinus = (float) Math.cos(Math.PI / 60); BaseFont bf = BaseFont.createFont(); over.beginText(); over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); over.setLineWidth(1.5f); over.setRGBColorStroke(0xFF, 0x00, 0x00); over.setRGBColorFill(0xFF, 0xFF, 0xFF); over.setFontAndSize(bf, 36); over.setTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324); over.showText("SOLD OUT"); over.endText(); over.restoreState(); // Add a rectangle under the image PdfContentByte under = writer.getDirectContentUnder(); under.saveState(); under.setRGBColorFill(0xFF, 0xD7, 0x00); under.rectangle(5, 5, PageSize.POSTCARD.getWidth() - 10, PageSize.POSTCARD.getHeight() - 10); under.fill(); under.restoreState(); // step 4 document.close(); }
public static void main(String[] args) throws IOException, DocumentException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("results/simple_rowspan_colspan.pdf")); document.open(); PdfPTable table = new PdfPTable(5); table.setWidths(new int[] {1, 2, 2, 2, 1}); PdfPCell cell; cell = new PdfPCell(new Phrase("S/N")); cell.setRowspan(2); table.addCell(cell); cell = new PdfPCell(new Phrase("Name")); cell.setColspan(3); table.addCell(cell); cell = new PdfPCell(new Phrase("Age")); cell.setRowspan(2); table.addCell(cell); table.addCell("SURNAME"); table.addCell("FIRST NAME"); table.addCell("MIDDLE NAME"); table.addCell("1"); table.addCell("James"); table.addCell("Fish"); table.addCell("Stone"); table.addCell("17"); document.add(table); document.close(); }
/** Generates a PDF with the list of registered members in the event. */ public void print() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "inline=filename=file.pdf"); try { Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); EventAttendeeReport eventAttendeeReport = new EventAttendeeReport(document); eventAttendeeReport.printReport(this.attendees); document.close(); response.getOutputStream().write(baos.toByteArray()); response.getOutputStream().flush(); response.getOutputStream().close(); context.responseComplete(); } catch (IOException | DocumentException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } }
/** * Creates a PDF file: hello_mirrored_margins.pdf * * @param args no arguments needed */ public static void main(String[] args) throws DocumentException, IOException { // step 1 Document document = new Document(); // step 2 PdfWriter.getInstance(document, new FileOutputStream(RESULT)); // setting page size, margins and mirrered margins document.setPageSize(PageSize.A5); document.setMargins(36, 72, 108, 180); document.setMarginMirroringTopBottom(true); // step 3 document.open(); // step 4 document.add( new Paragraph( "The left margin of this odd page is 36pt (0.5 inch); " + "the right margin 72pt (1 inch); " + "the top margin 108pt (1.5 inch); " + "the bottom margin 180pt (2.5 inch).")); Paragraph paragraph = new Paragraph(); paragraph.setAlignment(Element.ALIGN_JUSTIFIED); for (int i = 0; i < 20; i++) { paragraph.add( "Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!"); } document.add(paragraph); document.add(new Paragraph("The top margin 180pt (2.5 inch).")); // step 5 document.close(); }
public static void main(String[] args) throws FileNotFoundException, DocumentException { Document document = new Document(); @SuppressWarnings("unused") PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf")); document.open(); Paragraph paragraph1 = new Paragraph("This is Paragraph 1"); Paragraph paragraph2 = new Paragraph("This is Paragraph 2"); paragraph1.setIndentationLeft(80); paragraph1.setIndentationRight(80); paragraph1.setAlignment(Element.ALIGN_CENTER); paragraph1.setSpacingAfter(15); paragraph2.setSpacingBefore(15); paragraph2.setAlignment(Element.ALIGN_LEFT); Phrase phrase = new Phrase("This is a large sentence."); for (int count = 0; count < 10; count++) { paragraph1.add(phrase); paragraph2.add(phrase); } document.add(paragraph1); document.add(paragraph2); document.close(); }
/** * Converts the given txt file to pdf. It writes the result into the file by the name given in the * outputFileName variable. * * @param inputFileName the name of a text file to convert to PDF * @param encoding used by the file * @param outputFontName for Polish files recommended is to use "lucon.ttf" * @param fontSize the size of font to use in the pdf * @param isLandscapeMode if true the pdf pages will be in landscape otherwise they are in * portrait * @param outputFileName the name of a pdf file to convert to * @throws DocumentException * @throws IOException */ public static void convertTextToPDFFile( String inputFileName, String encoding, String outputFontName, float fontSize, boolean isLandscapeMode, String outputFileName) throws DocumentException, IOException { String fileContent = ReadWriteTextFileWithEncoding.read(inputFileName, encoding); // fileContent = fileContent.replaceAll("\t", tabAsSpaces); // System.out.println("??? czy zawiera ten char ("+newPageChar+") -1 znaczy brak="+ // fileContent.indexOf(newPageChar)); // System.out.println("fileContent="+fileContent); Rectangle pageSize = PageSize.A4; if (isLandscapeMode) pageSize = PageSize.A4.rotate(); Document document = new Document(pageSize); // we'll create the file in memory ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); // stworz czcionke kompatibilna z polskimi literami/kodowaniem BaseFont bf = BaseFont.createFont(outputFontName, encoding, BaseFont.EMBEDDED); Font font = new Font(bf, fontSize); Paragraph par = new Paragraph(fileContent, font); document.add(par); document.close(); // let's write the file in memory to a file anyway FileOutputStream fos = new FileOutputStream(outputFileName); fos.write(baos.toByteArray()); fos.close(); System.out.println("Convertion finished, result stored in file '" + outputFileName + "'"); }
public static void main(String[] args) { try { // Step 1: Init document Document document = new Document(); // Step 2: Init pdf file String file = "Pdf.pdf"; // Default will 'pdf' project folder PdfWriter.getInstance(document, new FileOutputStream(file)); // Step 3: Open document document.open(); // Step 4: Add connent Paragraph paragraph = new Paragraph("This is content"); document.add(paragraph); // ... // Step 5: Close document document.close(); System.out.println("OK"); } catch (Exception e) { e.printStackTrace(); } }
public Document createdocument(String filename) throws FileNotFoundException, DocumentException { Rectangle pagesize = new Rectangle(1650f, 800f); Document document = new Document(pagesize); PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); return document; }
@Override public byte[] buildReportFromFiche(Fiche fiche) throws DocumentException { logger.debug("Début méthode exportation PDF"); if (fiche.getAdresse() == null) { throw new BusinessException( "Impossible d'imprimer cette fiche : L'adresse n'est pas remplie."); } ByteArrayOutputStream bstream = new ByteArrayOutputStream(); logger.debug("Génération du PDF"); Document document = new Document(); PdfWriter.getInstance(document, bstream); document = buildMetadata(document, fiche); document.open(); document.add(buildHeader(fiche)); document.add(buildInfos(fiche)); document.add(buildSaisine(fiche)); document.add(buildExpose(fiche)); document.add(buildPersonnes(fiche)); document.add(buildProcedures(fiche)); document.close(); logger.debug("Fin de génération"); return bstream.toByteArray(); }
public static void exportImg() { Document document = null; try { // BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", // BaseFont.NOT_EMBEDDED);// 设置中文字体 // Font headFont = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小 document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("D:/test/img.pdf")); // 设定文档的作者 document.addAuthor("林计钦"); // 测试无效 document.open(); document.add(new Paragraph("你好,Img!")); // 读取一个图片 Image image = Image.getInstance("D:/test/1.jpg"); // 插入一个图片 document.add(image); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (document != null) { document.close(); } } }
public static void main(String[] args) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream("ImageRotation.pdf")); document.open(); // // Rotate image in radian using the setRotation method. // String filename = "other-sample/src/main/resources/java.gif"; Image image = Image.getInstance(filename); image.setRotation(90f); document.add(image); // // Rotate image in degree using the setRotationDegree method // String url = "http://localhost/xampp/img/xampp-logo-new.gif"; image = Image.getInstance(url); image.setRotationDegrees(90); document.add(image); } catch (DocumentException | IOException e) { e.printStackTrace(); } finally { document.close(); } }
private File convertPdfToPdfA(final InputStream source) throws IOException, DocumentException { final File pdfAFile = TempFileProvider.createTempFile("digitalSigning-" + System.currentTimeMillis(), ".pdf"); // Reads a PDF document. PdfReader reader = new PdfReader(source); // PdfStamper: Applies extra content to the pages of a PDF document. This extra content can be // all the objects allowed in // PdfContentByte including pages from other Pdfs. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfAFile)); // A generic Document class. Document document = new Document(); // we create a writer that listens to the document PdfWriter writer = stamper.getWriter(); int numberPages = reader.getNumberOfPages(); writer.setPDFXConformance(PdfWriter.PDFA1A); document.open(); // PdfDictionary:A dictionary is an associative table containing pairs of objects. // The first element of each pair is called the key and the second element is called the value // <CODE>PdfName</CODE> is an object that can be used as a name in a PDF-file PdfDictionary outi = new PdfDictionary(PdfName.OUTPUTINTENT); outi.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.S, PdfName.GTS_PDFA1); writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(outi)); // Add pages PdfImportedPage p = null; Image image; for (int i = 0; i < numberPages; i++) { p = writer.getImportedPage(reader, i + 1); image = Image.getInstance(p); document.add(image); } writer.createXmpMetadata(); document.close(); // Add Metadata from source pdf HashMap<String, String> info = reader.getInfo(); stamper.setMoreInfo(info); stamper.close(); return pdfAFile; }
/** * Creates a PDF document. * * @param filename the path to the new PDF document * @param locale Locale in case you want to create a Calendar in another language * @param year the year for which you want to make a calendar * @throws DocumentException * @throws IOException */ public void createPdf(String filename, Locale locale, int year) throws IOException, DocumentException { // step 1 Document document = new Document(PageSize.A4.rotate()); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT)); // step 3 document.open(); // step 4 PdfPTable table; Calendar calendar; PdfContentByte canvas = writer.getDirectContent(); // Loop over the months for (int month = 0; month < 12; month++) { calendar = new GregorianCalendar(year, month, 1); // draw the background drawImageAndText(canvas, calendar); // create a table with 7 columns table = new PdfPTable(7); table.setTableEvent(tableBackground); table.setTotalWidth(504); // add the name of the month table.getDefaultCell().setBorder(PdfPCell.NO_BORDER); table.getDefaultCell().setCellEvent(whiteRectangle); table.addCell(getMonthCell(calendar, locale)); int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); int day = 1; int position = 2; // add empty cells while (position != calendar.get(Calendar.DAY_OF_WEEK)) { position = (position % 7) + 1; table.addCell(""); } // add cells for each day while (day <= daysInMonth) { calendar = new GregorianCalendar(year, month, day++); table.addCell(getDayCell(calendar, locale)); } // complete the table table.completeRow(); // write the table to an absolute position table.writeSelectedRows(0, -1, 169, table.getTotalHeight() + 20, canvas); document.newPage(); } // step 5 document.close(); }
/** * Creates a PDF document. * * @param filename the path to the new PDF document * @throws DocumentException * @throws IOException * @throws BadLocationException */ public void createPdf(String filename) throws IOException, DocumentException, BadLocationException { Document document = new Document(new Rectangle(300, 150)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); PdfContentByte canvas = writer.getDirectContent(); DefaultFontMapper mapper = new DefaultFontMapper(); BaseFontParameters parameters = new BaseFontParameters("c:/windows/fonts/msgothic.ttc,1"); parameters.encoding = BaseFont.IDENTITY_H; mapper.putName("MS PGothic", parameters); Graphics2D g2 = canvas.createGraphics(300, 150, mapper); JTextPane text = TextExample4.createTextPane(); text.setSize(new Dimension(300, 150)); text.print(g2); g2.dispose(); document.close(); }
/** * Constructor. Takes in a string representing where the file should be written to disk. * * @param fname * @throws DocumentException * @throws FileNotFoundException */ public BarcodePdf(String fname) throws FileNotFoundException, DocumentException { _d = new Document(); _writer = PdfWriter.getInstance(_d, new FileOutputStream(fname)); _d.setMargins(25, 25, 25, 25); _d.open(); _open = true; _rawContent = _writer.getDirectContent(); _table = new PdfPTable(4); _table.setHorizontalAlignment(Element.ALIGN_CENTER); _itemsAdded = 0; }