List of usage examples for com.lowagie.text.pdf PdfContentByte createGraphics
public java.awt.Graphics2D createGraphics(float width, float height)
Graphics2D
to write on. From source file:classroom.intro.HelloWorld10.java
public static void main(String[] args) { // step 1//ww w. ja va2 s .com Document.compress = false; Document document = new Document(); try { // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT)); // step 3 document.open(); // step 4 PdfContentByte cb = writer.getDirectContent(); Graphics2D graphics2D = cb.createGraphics(PageSize.A4.getWidth(), PageSize.A4.getHeight()); graphics2D.drawString("Hello World", 36, 54); graphics2D.dispose(); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5 document.close(); }
From source file:com.matic.sudoku.io.export.PdfExporter.java
License:Open Source License
/** * Write board contents to PDF/*from w w w. j a v a 2 s. c o m*/ * * @param board The board to write * @param targetFile Target output PDF file to write to * @throws DocumentException If any PDF library error occurs * @throws IOException If any error occurs while writing the PDF file */ public void write(final Board board, final File targetFile) throws DocumentException, IOException { //FontFactory.defaultEmbedding = true; final Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN); final OutputStream outputStream = new FileOutputStream(targetFile); final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); document.open(); final PdfContentByte contentByte = pdfWriter.getDirectContent(); final Rectangle pageSize = document.getPageSize(); final float pageHeight = pageSize.getHeight(); final float pageWidth = pageSize.getWidth(); contentByte.saveState(); final Graphics2D g2d = contentByte.createGraphics(pageWidth, pageHeight); board.setSize((int) pageWidth, (int) pageWidth); board.handleResized(); final int puzzleWidth = board.getPuzzleWidth(); //Calculate x and y coordinates for centered game board final int originX = (int) (pageWidth / 2 - (puzzleWidth / 2)); final int originY = (int) ((pageHeight / 2) - (puzzleWidth / 2)); board.setDrawingOrigin(originX, originY); board.draw(g2d, true, false); contentByte.restoreState(); g2d.dispose(); document.close(); outputStream.flush(); outputStream.close(); }
From source file:com.matic.sudoku.io.export.PdfExporter.java
License:Open Source License
/** * Generate and export multiple boards to PDF * /*from www.j av a 2 s . c o m*/ * @param exporterParameters PDF exporter parameters * @param generator Generator used for puzzle generation * @throws IOException If any PDF library error occurs * @throws DocumentException If any error occurs while writing the PDF file */ public void write(final ExporterParameters exporterParameters, final Generator generator, final int boardDimension) throws IOException, DocumentException { //How many PDF-pages are needed to fit all puzzles using the desired page formatting final int optimisticPageCount = exporterParameters.getPuzzleCount() / exporterParameters.getPuzzlesPerPage(); final int pageCount = exporterParameters.getPuzzleCount() % exporterParameters.getPuzzlesPerPage() > 0 ? optimisticPageCount + 1 : optimisticPageCount; final Document document = new Document(PageSize.A4, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN, DOCUMENT_MARGIN); final OutputStream outputStream = new FileOutputStream(exporterParameters.getOutputPath()); final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); final String creator = Sudoku.getNameAndVersion(); document.addSubject("Puzzles generated by " + creator); document.addCreator(creator); document.open(); final Rectangle pageSize = document.getPageSize(); final int pageHeight = (int) pageSize.getHeight(); final int pageWidth = (int) pageSize.getWidth(); //Get appropriate number of rows and columns needed to divide a page into final int horizontalDimension = exporterParameters.getPuzzlesPerPage() > 2 ? 2 : 1; final int verticalDimension = exporterParameters.getPuzzlesPerPage() > 1 ? 2 : 1; //Get available space for each board (with margins) on a page final int boardWidth = pageWidth / horizontalDimension; final int boardHeight = pageHeight / verticalDimension; final Board board = new Board(boardDimension, SymbolType.DIGITS); board.setSize(boardWidth, boardHeight); board.handleResized(); //Get available height/width on a page for a puzzle itself final int puzzleWidth = board.getPuzzleWidth(); int puzzlesPrinted = 0; final PdfContentByte contentByte = pdfWriter.getDirectContent(); final Grading[] gradings = getGeneratedPuzzleGradings(exporterParameters.getGradings(), exporterParameters.getOrdering(), exporterParameters.getPuzzleCount()); pageCounter: for (int page = 0; page < pageCount; ++page) { document.newPage(); final Graphics2D g2d = contentByte.createGraphics(pageWidth, pageHeight); for (int y = 0, i = 0; i < verticalDimension; y += boardHeight, ++i) { for (int x = 0, j = 0; j < horizontalDimension; x += boardWidth, ++j) { //Check whether to generate a new puzzle or print empty boards final ExportMode exportMode = exporterParameters.getExportMode(); final Grading selectedGrading = exportMode == ExportMode.BLANK ? null : gradings[puzzlesPrinted]; if (exportMode == ExportMode.GENERATE_NEW) { board.setPuzzle(generatePuzzle(generator, getSymmetry(exporterParameters.getSymmetries()), selectedGrading)); board.recordGivens(); } //Calculate puzzle drawing origins final int originX = x + (int) (boardWidth / 2 - (puzzleWidth / 2)); final int originY = y + (int) (boardHeight / 2) - (puzzleWidth / 2); board.setSymbolType(getSymbolType(exporterParameters.getSymbolType())); board.setDrawingOrigin(originX, originY); board.draw(g2d, false, false); drawLegend(g2d, getLegendString(exporterParameters.isShowNumbering(), exporterParameters.isShowGrading(), puzzlesPrinted + 1, selectedGrading), originX, originY, puzzleWidth); if (++puzzlesPrinted == exporterParameters.getPuzzleCount()) { //We've printed all puzzles, break g2d.dispose(); break pageCounter; } } } g2d.dispose(); } document.close(); outputStream.flush(); outputStream.close(); }
From source file:com.umlet.control.io.GenPdf.java
License:Open Source License
public void createPdfToStream(OutputStream ostream, DiagramHandler handler) { try {/*from ww w. j a v a2s . c o m*/ // We get the Rectangle of our DrawPanel java.awt.Rectangle bounds = handler.getDrawPanel().getContentBounds(Constants.PRINTPADDING); // and create an iText specific Rectangle from (0,0) to (width,height) in which we draw the diagram Rectangle drawSpace = new Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()); // Create document in which we write the pdf Document document = new Document(drawSpace); PdfWriter writer = PdfWriter.getInstance(document, ostream); document.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D graphics2d = cb.createGraphics(drawSpace.getWidth(), drawSpace.getHeight()); // We shift the diagram to the upper left corner, so we shift it by (minX,minY) of the contextBounds Dimension trans = new Dimension((int) bounds.getMinX(), (int) bounds.getMinY()); graphics2d.translate(-trans.getWidth(), -trans.getHeight()); handler.getDrawPanel().paintEntitiesIntoGraphics2D(graphics2d); graphics2d.dispose(); document.close(); } catch (Exception e) { System.out.println("UMLet: Error: Exception in outputPdf: " + e); } }
From source file:gui.TransHistory.java
public void Convertpdf() throws Exception { display();// w w w .j a v a 2 s .c o m Document document = new Document(PageSize.A4.rotate()); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Table.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Graphics2D g2 = cb.createGraphics(500, 500); Shape oldClip = g2.getClip(); g2.clipRect(20, 20, 500, 500); jTable1.print(g2); jTable1.getTableHeader().paint(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); cb.saveState(); } catch (Exception e) { System.err.println(e.getMessage()); } document.close(); //send mail query = "select email from profile_id where user_id = ?"; psmt = con.prepareStatement(query); psmt.setString(1, t.user); rs = psmt.executeQuery(); rs.next(); SendMailWithAttachment smail = new SendMailWithAttachment(); String message = "hereby is the requested transction report of account " + "no. = " + t.accNo + " from date " + fDate + " to " + toDate; smail.send(rs.getString(1), "Table.pdf", message); }
From source file:jdraw.JDrawApplication.java
private void saveAsPDF() { JDocumentFrame frame = (JDocumentFrame) jDesktopPane1.getSelectedFrame(); if (frame == null) { return;// w w w . j av a 2s . c o m } JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter( java.util.ResourceBundle.getBundle("main").getString("filter_pdf"), "pdf")); chooser.setDialogTitle(java.util.ResourceBundle.getBundle("main").getString("dialog_export_as_pdf")); File f = chooser.getCurrentDirectory(); f = new File(f.getPath(), frame.getDocument().getName() + ".pdf"); chooser.setSelectedFile(f); if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } JDocument doc = frame.getDocument(); f = chooser.getSelectedFile(); if (f.exists() && JOptionPane.showConfirmDialog(this, f.getName() + java.util.ResourceBundle .getBundle("main").getString("msg_is_exist_overwrite")) != JOptionPane.OK_OPTION) { return; } frame.getViewer().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); com.lowagie.text.Document pDoc = new com.lowagie.text.Document(); try { FileOutputStream wt = new FileOutputStream(f); BufferedOutputStream bout = new BufferedOutputStream(wt); com.lowagie.text.pdf.PdfWriter pwriter = com.lowagie.text.pdf.PdfWriter.getInstance(pDoc, bout); pDoc.open(); FontFactory.registerDirectories(); Set set = FontFactory.getRegisteredFonts(); for (int i = 0; i < doc.size(); i++) { JPage cPage = doc.get(i); PageFormat pFormat = cPage.getPageFormat(); com.lowagie.text.Rectangle rc = new com.lowagie.text.Rectangle((float) pFormat.getWidth(), (float) pFormat.getHeight()); float left = (float) (pFormat.getImageableX()); float right = (float) (pFormat.getWidth() - pFormat.getImageableWidth() - left); float top = (float) pFormat.getImageableX(); float bottom = (float) (pFormat.getHeight() - pFormat.getImageableHeight() - top); pDoc.newPage(); com.lowagie.text.pdf.PdfContentByte cb = pdfContentByte = pwriter.getDirectContent(); cb.saveState(); Graphics2D g2 = (com.lowagie.text.pdf.PdfGraphics2D) cb.createGraphics((float) pFormat.getWidth(), (float) pFormat.getHeight()); boolean vg = cPage.getGuidLayer().isVisible(); cPage.getGuidLayer().setVisible(false); cPage.paint(new Rectangle.Double(0, 0, pFormat.getWidth(), pFormat.getHeight()), g2); cPage.getGuidLayer().setVisible(vg); g2.dispose(); cb.restoreState(); } pDoc.close(); } catch (Exception e) { JOptionPane.showConfirmDialog(this, e.getMessage(), "", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE); } frame.getViewer().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }
From source file:net.refractions.udig.printing.ui.internal.PdfPrintingEngine.java
License:Open Source License
public boolean printToPdf() { Dimension paperSize = page.getPaperSize(); Dimension pageSize = page.getSize(); float xScale = (float) paperSize.width / (float) pageSize.width; float yScale = (float) paperSize.height / (float) pageSize.height; Rectangle paperRectangle = new Rectangle(paperSize.width, paperSize.height); Document document = new Document(paperRectangle, 0f, 0f, 0f, 0f); try {/*from ww w . j a v a 2s. c om*/ PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPdfFile)); document.open(); PdfContentByte cb = writer.getDirectContent(); Graphics2D graphics = cb.createGraphics(paperRectangle.getWidth(), paperRectangle.getHeight()); // BufferedImage bI = new BufferedImage((int) paperRectangle.width(), (int) // paperRectangle // .height(), BufferedImage.TYPE_INT_ARGB); // Graphics graphics2 = bI.getGraphics(); List<Box> boxes = page.getBoxes(); for (Box box : boxes) { String id = box.getID(); System.out.println(id); Point boxLocation = box.getLocation(); if (boxLocation == null) continue; int x = boxLocation.x; int y = boxLocation.y; Dimension size = box.getSize(); if (size == null) continue; int w = size.width; int h = size.height; float newX = xScale * (float) x; float newY = yScale * (float) y; float newW = xScale * (float) w; float newH = yScale * (float) h; box.setSize(new Dimension((int) newW, (int) newH)); box.setLocation(new Point((int) newX, (int) newY)); Graphics2D boxGraphics = (Graphics2D) graphics.create((int) newX, (int) newY, (int) newW, (int) newH); BoxPrinter boxPrinter = box.getBoxPrinter(); boxPrinter.draw(boxGraphics, monitor); } graphics.dispose(); // ImageIO.write(bI, "png", new File("c:\\Users\\moovida\\Desktop\\test.png")); // graphics.drawImage(bI, null, 0, 0); document.newPage(); document.close(); writer.close(); } catch (DocumentException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; }
From source file:org.deegree.igeo.commands.VectorPrintCommand.java
License:Open Source License
/** * initializes the {@link Document} required for printing using iText * /* ww w.jav a 2 s . c om*/ * @return graphic context ({@link Graphics2D}) of the initialized document * @throws FileNotFoundException * @throws DocumentException */ private Graphics2D initDocument() throws FileNotFoundException, DocumentException { String pageFormat = printDefinition.getPageFormat(); Rectangle pageSize; if (pageFormat != null) pageSize = PageSize.getRectangle(pageFormat); else pageSize = new Rectangle(printDefinition.getPageWidth(), printDefinition.getPageHeight()); LOG.logDebug("page size", pageSize); // create (pdf) document with selected pages size; set margin and PDF-version document = new Document(pageSize); document.setMargins(printDefinition.getAreaLeft(), printDefinition.getAreaLeft() + printDefinition.getAreaWidth(), printDefinition.getAreaTop(), printDefinition.getAreaTop() + printDefinition.getAreaHeight()); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(printDefinition.getTargetFile())); writer.setPdfVersion(printDefinition.getPdfVersion()); document.open(); PdfContentByte cb = writer.getDirectContent(); // create canvas Graphics2D g = cb.createGraphics(convert(pageSize.getWidth() / 72 * 25.4), convert(pageSize.getHeight() / 72 * 25.4)); LOG.logDebug("canvas size", convert(pageSize.getWidth() / 72 * 25.4) + " " + convert(pageSize.getHeight() / 72 * 25.4)); // required for correct scaling of raster symbols int i1 = convert(pageSize.getHeight() / 72 * 25.4); int i2 = convert_(pageSize.getHeight() / 72 * 25.4); g.translate(0, i1 - i2); g.scale(72d / printDefinition.getDpi(), 72d / printDefinition.getDpi()); return g; }
From source file:org.encog.workbench.util.graph.DocumentPDF.java
License:Apache License
public static void savePDF(File filename, JFreeChart chart, int width, int height) { try {/* ww w . j a v a2s . c om*/ // step 1 Document document = new Document(new Rectangle(width, height)); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfContentByte canvas = writer.getDirectContent(); Graphics2D g2 = canvas.createGraphics(width, height); Rectangle2D area = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2, area); g2.dispose(); // step 5 document.close(); } catch (DocumentException ex) { throw new WorkBenchError(ex); } catch (IOException ex) { throw new WorkBenchError(ex); } }
From source file:org.interpss.editor.codecs.FileExportPDF.java
License:Open Source License
/** * @see java.awt.event.ActionListener#actionPerformed(ActionEvent) *//*from w w w.j av a 2 s .c o m*/ public void actionPerformed(ActionEvent e) { Document document = new Document(); try { String file = saveDialog(Translator.getString("FileSaveAsLabel") + " " + fileType.toUpperCase(), fileType.toLowerCase(), fileType.toUpperCase() + " Image"); if (file == null) return; JGraph graph = getCurrentGraph(); Object[] cells = graph.getDescendants(graph.getRoots()); if (cells.length > 0 && file != null && file.length() > 0) { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); Rectangle2D bounds = graph.getCellBounds(cells); graph.toScreen(bounds); Dimension d = bounds.getBounds().getSize(); Object[] selection = graph.getSelectionCells(); boolean gridVisible = graph.isGridVisible(); boolean doubleBuffered = graph.isDoubleBuffered(); graph.setGridVisible(false); graph.setDoubleBuffered(false); graph.clearSelection(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); cb.concatCTM(1, 0, 0, 1, 50, 400); Graphics2D g2 = cb.createGraphics(d.width + 10, d.height + 10); g2.setColor(graph.getBackground()); g2.fillRect(0, 0, d.width + 10, d.height + 10); g2.translate(-bounds.getX() + 5, -bounds.getY() + 5); graph.paint(g2); graph.setSelectionCells(selection); graph.setGridVisible(gridVisible); graph.setDoubleBuffered(doubleBuffered); g2.dispose(); cb.restoreState(); } } catch (IOException ex) { graphpad.error(ex.getMessage()); } catch (DocumentException e2) { graphpad.error(e2.getMessage()); } document.close(); }