List of usage examples for com.itextpdf.text.pdf PdfContentByte createTemplate
public PdfTemplate createTemplate(final float width, final float height)
From source file:edu.umn.genomics.component.SavePDF.java
License:Open Source License
/** * Saves the Component to a Portable Document File, PDF, with the * file location selected using the JFileChooser. * @param c the Component to save as a PDF *//*w w w . jav a 2s . c om*/ public static boolean savePDF(Component c) throws IOException { System.out.println(""); final int w = c.getWidth() > 0 ? c.getWidth() : 1; final int h = c.getHeight() > 0 ? c.getHeight() : 1; final Dimension dim = c.getPreferredSize(); JFileChooser chooser = new JFileChooser(); JPanel ap = new JPanel(); ap.setLayout(new BoxLayout(ap, BoxLayout.Y_AXIS)); JPanel sp = new JPanel(new GridLayout(0, 1)); sp.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Image Size")); final JTextField iwtf = new JTextField("" + w, 4); iwtf.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "width")); final JTextField ihtf = new JTextField("" + h, 4); ihtf.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "height")); JButton curSzBtn = new JButton("As Viewed: " + w + "x" + h); curSzBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { iwtf.setText("" + w); ihtf.setText("" + h); } }); sp.add(curSzBtn); if (dim != null && dim.getWidth() > 0 && dim.getHeight() > 0) { JButton prefSzBtn = new JButton("As Preferred: " + dim.width + "x" + dim.height); prefSzBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { iwtf.setText("" + dim.width); ihtf.setText("" + dim.height); } }); sp.add(prefSzBtn); } sp.add(iwtf); sp.add(ihtf); ap.add(sp); chooser.setAccessory(ap); // ImageFilter filter = new ImageFilter(fmt); // chooser.setFileFilter(filter); int returnVal = chooser.showSaveDialog(c); boolean status = false; if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); //Added the below code to add th .pdf extension if it is not provided by the user String name = file.getAbsolutePath(); if (!(name.substring(name.length() - 4, name.length()).equalsIgnoreCase(".pdf"))) { name = name.concat(".pdf"); file = new File(name); } int iw = w; int ih = h; try { iw = Integer.parseInt(iwtf.getText()); ih = Integer.parseInt(ihtf.getText()); } catch (Exception ex) { ExceptionHandler.popupException("" + ex); } iw = iw > 0 ? iw : w; ih = ih > 0 ? ih : h; if (iw != w || ih != h) { c.setSize(iw, ih); } // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); // step 3: we open the document document.open(); // step 4: we grab the ContentByte and do some stuff with it // we create a fontMapper and read all the fonts in the font directory DefaultFontMapper mapper = new DefaultFontMapper(); // mapper.insertDirectory("c:\\winnt\\fonts"); com.itextpdf.text.Rectangle pgSize = document.getPageSize(); // we create a template and a Graphics2D object that corresponds with it PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(iw, ih); tp.setWidth(iw); tp.setHeight(ih); Graphics2D g2 = tp.createGraphics(iw, ih, mapper); g2.setStroke(new BasicStroke(.1f)); //cb.setLineWidth(.1f); //cb.stroke(); c.paintAll(g2); g2.dispose(); //cb.addTemplate(tp, 0, 0); float sfx = (float) (pgSize.getWidth() / iw); float sfy = (float) (pgSize.getHeight() / ih); // preserve the aspect ratio float sf = (float) Math.min(sfx, sfy); cb.addTemplate(tp, sf, 0f, 0f, sf, 0f, 0f); } catch (DocumentException de) { ExceptionHandler.popupException("" + de); } catch (IOException ioe) { ExceptionHandler.popupException("" + ioe); } catch (Exception ex) { ExceptionHandler.popupException("" + ex); } // step 5: we close the document document.close(); if (iw != w || ih != h) { c.setSize(w, h); } } return true; }
From source file:figtree.application.FigTreeFrame.java
License:Open Source License
public final void doExportPDF() { FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE); dialog.setVisible(true);/*from www . j a v a 2 s. com*/ if (dialog.getFile() != null) { File file = new File(dialog.getDirectory(), dialog.getFile()); Rectangle2D bounds = treeViewer.getContentPane().getBounds(); Document document = new Document( new com.itextpdf.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight())); try { // step 2 PdfWriter writer; writer = PdfWriter.getInstance(document, new FileOutputStream(file)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight()); Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper()); treeViewer.getContentPane().print(g2d); g2d.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error", JOptionPane.ERROR_MESSAGE); } document.close(); } }
From source file:figtree.application.FigTreePDF.java
License:Open Source License
static public void createGraphic(int width, int height, String treeFileName, String graphicFileName) { try {// ww w . jav a2 s . c om BufferedReader bufferedReader = new BufferedReader(new FileReader(treeFileName)); String line = bufferedReader.readLine(); while (line != null && line.length() == 0) { line = bufferedReader.readLine(); } bufferedReader.close(); boolean isNexus = (line != null && line.toUpperCase().contains("#NEXUS")); Reader reader = new FileReader(treeFileName); Map<String, Object> settings = new HashMap<String, Object>(); ExtendedTreeViewer treeViewer = new ExtendedTreeViewer(); ControlPalette controlPalette = new BasicControlPalette(200, BasicControlPalette.DisplayMode.ONLY_ONE_OPEN); FigTreePanel figTreePanel = new FigTreePanel(null, treeViewer, controlPalette); // First of all, fully populate the settings map so that // all the settings have defaults controlPalette.getSettings(settings); List<Tree> trees = new ArrayList<Tree>(); if (isNexus) { FigTreeNexusImporter importer = new FigTreeNexusImporter(reader); trees.add(importer.importNextTree()); // Try to find a figtree block and if found, parse the settings while (true) { try { importer.findNextBlock(); if (importer.getNextBlockName().equalsIgnoreCase("FIGTREE")) { importer.parseFigTreeBlock(settings); } } catch (EOFException ex) { break; } } } else { NewickImporter importer = new NewickImporter(reader, true); trees.add(importer.importNextTree()); } if (trees.size() == 0) { throw new ImportException("This file contained no trees."); } treeViewer.setTrees(trees); controlPalette.setSettings(settings); treeViewer.getContentPane().setSize(width, height); OutputStream stream; if (graphicFileName != null) { stream = new FileOutputStream(graphicFileName); } else { stream = System.out; } Document document = new Document(); document.setPageSize(new com.itextpdf.text.Rectangle(width, height)); try { PdfWriter writer = PdfWriter.getInstance(document, stream); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height); tp.setWidth(width); tp.setHeight(height); treeViewer.getContentPane().print(g2); g2.dispose(); tp.sanityCheck(); // all the g2 content is written to tp, not cb cb.addTemplate(tp, 0, 0); cb.sanityCheck(); } catch (Exception e) { System.err.println(e.getMessage()); } document.close(); } catch (ImportException ie) { throw new RuntimeException("Error writing graphic file: " + ie); } catch (IOException ioe) { throw new RuntimeException("Error writing graphic file: " + ioe); } }
From source file:GeMSE.Popups.PopupMenuType.java
License:Open Source License
private void SaveAsPDF(java.awt.event.ActionEvent e, File file) { Document document = new Document(new Rectangle(_component.getSize().width, _component.getSize().height)); try {//ww w .j a va 2 s .com PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(_component.getSize().width, _component.getSize().height); Graphics graphics = new PdfGraphics2D(template, _component.getSize().width, _component.getSize().height); _component.print(graphics); graphics.dispose(); contentByte.addTemplate(template, 0, 0); } catch (DocumentException | FileNotFoundException e2) { } finally { if (document.isOpen()) document.close(); } }
From source file:GeMSE.Visualization.Graph.GraphVis.java
License:Open Source License
private void SaveAsPDF(File file) { Document document = new Document(new Rectangle(graphPanel.getSize().width, graphPanel.getSize().height)); try {/*from w ww . j a va 2s . c o m*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(graphPanel.getSize().width, graphPanel.getSize().height); Graphics graphics = new PdfGraphics2D(template, graphPanel.getSize().width, graphPanel.getSize().height); graphPanel.print(graphics); graphics.dispose(); contentByte.addTemplate(template, 0, 0); } catch (DocumentException | FileNotFoundException e2) { } finally { if (document.isOpen()) document.close(); } }
From source file:info.sarihh.unimodeling.gui.DynamicBPEstimateFrame.java
public static void writeChartAsPDF(OutputStream out, JFreeChart chart, int width, int height, FontMapper mapper) throws IOException { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); try {/* w ww .ja v a2 s . com*/ PdfWriter writer = PdfWriter.getInstance(document, out); document.addAuthor("JFreeChart"); document.addSubject("Demonstration"); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, mapper); Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, r2D, null); g2.dispose(); cb.addTemplate(tp, 0, 0); } catch (DocumentException de) { System.err.println(de.getMessage()); } document.close(); }
From source file:Login.ventas.fproyectos.java
public void fondos(Document documento, PdfContentByte canvas) { try {/*w ww . j a v a2s. c o m*/ Image imghead = Image.getInstance(usuario.getDireccion() + "/plantilla.jpg"); imghead.setAbsolutePosition(0, 0); imghead.setAlignment(Image.ALIGN_CENTER); float scaler = ((documento.getPageSize().getWidth() - documento.leftMargin() - documento.rightMargin()) / imghead.getWidth()) * 100; imghead.scalePercent(scaler); PdfTemplate tp = canvas.createTemplate(PageSize.A4.getWidth(), PageSize.A4.getHeight()); //el rea destinada para el encabezado tp.addImage(imghead); x = (int) imghead.getWidth(); y = (int) imghead.getHeight(); canvas.addTemplate(tp, 0, 0);//posicin del tmplate derecha y abajo } catch (IOException | DocumentException io) { } }
From source file:matheos.texte.OngletTexte.java
License:Open Source License
public void export2Pdf(final File f) { final Formatter formatter = editeur.getFormatter(); new Thread(new Runnable() { @Override/*from ww w . j a v a2 s. c om*/ public void run() { FileOutputStream fos = null; try { fos = new FileOutputStream(f); Document document = new Document(); Book book = formatter.createBook(); try { PdfWriter writer = PdfWriter.getInstance(document, fos); document.open(); PdfContentByte canvas = writer.getDirectContent(); for (int i = 0; i < book.getNumberOfPages(); i++) { document.newPage(); PageFormat page = book.getPageFormat(i); PdfTemplate templ = canvas.createTemplate((float) page.getWidth(), (float) page.getHeight()); Graphics2D g2 = templ.createGraphics((float) page.getWidth(), (float) page.getHeight()); try { book.getPrintable(i).print(g2, book.getPageFormat(i), i); } catch (PrinterException ex) { Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex); } canvas.addTemplate(templ, 0, 0); g2.dispose(); } } catch (DocumentException ex) { Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex); } finally { document.close(); } } catch (FileNotFoundException ex) { Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex); } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (IOException ex) { Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex); } } } } }).start(); }
From source file:mymoney.Multi_cal.java
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed getContentPane().setLayout(new BorderLayout()); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); JFileChooser cho = new JFileChooser(); cho.showSaveDialog(null);// w w w. ja v a 2s . c o m File f = cho.getSelectedFile(); String filename = f.getAbsolutePath(); com.itextpdf.text.Document document = new com.itextpdf.text.Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); PdfTemplate pdfTemplate = cb.createTemplate(jTable1.getWidth(), jTable1.getHeight()); Graphics2D g2 = cb.createGraphicsShapes(800, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 800, 500); jTable1.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); JOptionPane.showMessageDialog(null, "Data Exported to pdf"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error"); } document.close(); // TODO add your handling code here: }
From source file:mymoney.view.java
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed getContentPane().setLayout(new BorderLayout()); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); JFileChooser cho = new JFileChooser(); cho.showSaveDialog(null);// w ww . j av a 2 s . c o m File f = cho.getSelectedFile(); String filename = f.getAbsolutePath(); com.itextpdf.text.Document document = new com.itextpdf.text.Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename + ".pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); PdfTemplate pdfTemplate = cb.createTemplate(jTable1.getWidth(), jTable1.getHeight()); Graphics2D g2 = cb.createGraphicsShapes(800, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 800, 500); jTable1.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); JOptionPane.showMessageDialog(null, "Data Exported to pdf"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error"); } document.close(); // TODO add your handling code here: }