List of usage examples for com.itextpdf.text.pdf PdfTemplate setWidth
public void setWidth(float width)
From source file:com.centurylink.mdw.pdf.PdfExportHelper.java
License:Apache License
private void printGraph(DocWriter writer, ProcessCanvas canvas, Process process, Rectangle pageSize, Chapter chapter) throws Exception { Dimension graphsize = getGraphSize(process); // we create a template and a Graphics2D object that corresponds with it int w;// w w w .j a v a2 s . c o m int h; float scale; if ((float) graphsize.width < pageSize.getWidth() * 0.8 && (float) graphsize.height < pageSize.getHeight() * 0.8) { w = graphsize.width + 36; h = graphsize.height + 36; scale = -1f; } else { scale = pageSize.getWidth() * 0.8f / (float) graphsize.width; if (scale > pageSize.getHeight() * 0.8f / (float) graphsize.height) scale = pageSize.getHeight() * 0.8f / (float) graphsize.height; w = (int) (graphsize.width * scale) + 36; h = (int) (graphsize.height * scale) + 36; } Image img; canvas.setBackground(Color.white); PdfContentByte cb = ((PdfWriter) writer).getDirectContent(); PdfTemplate tp = cb.createTemplate(w, h); Graphics2D g2 = tp.createGraphics(w, h); if (scale > 0) g2.scale(scale, scale); tp.setWidth(w); tp.setHeight(h); canvas.paintComponent(g2); g2.dispose(); img = new ImgTemplate(tp); chapter.add(img); }
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 *//*from ww w . j a v a 2 s .c o m*/ 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.FigTreePDF.java
License:Open Source License
static public void createGraphic(int width, int height, String treeFileName, String graphicFileName) { try {//from ww w .ja va 2 s. c o m 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:ptolemy.vergil.basic.export.itextpdf.ExportPDFAction.java
License:Open Source License
/** Export PDF to a file. * This uses the iText library at http://itextpdf.com/. * * <p>If {@link ptolemy.gui.PtGUIUtilities#useFileDialog()} returns true * then a java.awt.FileDialog is used, otherwise a javax.swing.JFileChooser * is used.</p>// www .ja v a 2 s. c o m */ private void _exportPDF() { Dimension size = _frame.getContentSize(); Rectangle pageSize = null; try { pageSize = new Rectangle(size.width, size.height); } catch (Throwable ex) { // This exception will occur if the iText library is not installed. MessageHandler.error("iText library is not installed. See http://itextpdf.com/." + " You must have iText.jar in your classpath. Sometimes, " + "iText.jar may be found in $PTII/vendors/itext/iText.jar.", ex); return; } Document document = new Document(pageSize); JFileChooserBugFix jFileChooserBugFix = new JFileChooserBugFix(); Color background = null; PtFileChooser ptFileChooser = null; try { background = jFileChooserBugFix.saveBackground(); ptFileChooser = new PtFileChooser(_frame, "Specify a pdf file to be written.", JFileChooser.SAVE_DIALOG); LinkedList extensions = new LinkedList(); extensions.add("pdf"); ptFileChooser.addChoosableFileFilter(new ExtensionFilenameFilter(extensions)); BasicGraphFrame basicGraphFrame = null; if (_frame instanceof BasicGraphFrame) { basicGraphFrame = (BasicGraphFrame) _frame; ptFileChooser.setCurrentDirectory(basicGraphFrame.getLastDirectory()); ptFileChooser.setSelectedFile(new File(basicGraphFrame.getModel().getName() + ".pdf")); } int returnVal = ptFileChooser.showDialog(_frame, "Export PDF"); if (returnVal == JFileChooser.APPROVE_OPTION) { if (basicGraphFrame != null) { basicGraphFrame.setLastDirectory(ptFileChooser.getCurrentDirectory()); } File pdfFile = ptFileChooser.getSelectedFile().getCanonicalFile(); if (pdfFile.getName().indexOf(".") == -1) { // If the user has not given the file an extension, add it pdfFile = new File(pdfFile.getAbsolutePath() + ".pdf"); } // The Mac OS X FileDialog will ask if we want to save before this point. if (pdfFile.exists() && !PtGUIUtilities.useFileDialog()) { if (!MessageHandler.yesNoQuestion("Overwrite " + pdfFile.getName() + "?")) { return; } } PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile)); // To ensure Latex compatibility, use earlier PDF version. writer.setPdfVersion(PdfWriter.VERSION_1_3); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(size.width, size.height); Graphics2D graphics = template.createGraphics(size.width, size.height); template.setWidth(size.width); template.setHeight(size.height); Paper paper = new Paper(); paper.setSize(size.width, size.height); paper.setImageableArea(0.0, 0.0, size.width, size.height); PageFormat format = new PageFormat(); format.setPaper(paper); ((Printable) _frame).print(graphics, format, 0); graphics.dispose(); contentByte.addTemplate(template, 0, 0); // Open the PDF file. // FIXME: _read is protected in BasicGraphFrame //_read(pdfFile.toURI().toURL()); // Open the image pdfFile. if (basicGraphFrame == null) { MessageHandler.message("PDF file exported to " + pdfFile.getName()); /* Remove the following. The extra click is annoying... } else { if (MessageHandler.yesNoQuestion("Open \"" + pdfFile.getCanonicalPath() + "\" in a browser?")) { Configuration configuration = basicGraphFrame .getConfiguration(); try { URL imageURL = new URL(pdfFile.toURI().toURL() .toString() + "#in_browser"); configuration.openModel(imageURL, imageURL, imageURL.toExternalForm(), BrowserEffigy.staticFactory); } catch (Throwable throwable) { MessageHandler.error( "Failed to open \"" + pdfFile.getName() + "\".", throwable); } } */ } } } catch (Exception e) { MessageHandler.error("Export to PDF failed", e); } finally { try { document.close(); } finally { jFileChooserBugFix.restoreBackground(background); } } }