List of usage examples for com.lowagie.text.pdf PdfContentByte restoreState
public void restoreState()
From source file:com.t2.compassionMeditation.ViewSessionsActivity.java
License:Open Source License
/** * Create a PDF file based on the contents of the graph *//*ww w .ja v a 2s . com*/ void CreatePdf() { // Run the export on a separate thread. new Thread(new Runnable() { @Override public void run() { Document document = new Document(); try { Date calendar = Calendar.getInstance().getTime(); mResultsFileName = "BioZenResults_"; mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-" + calendar.getDate() + "_"; mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-" + calendar.getSeconds() + ".pdf"; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + mResultsFileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // Note top of PDF = 900 float chartWidth = 332; float chartHeight = 45; float spaceHeight = chartHeight + 30; int horizontalPos = 180; float verticalPos = 780; // Write document header contentByte.beginText(); contentByte.setFontAndSize(baseFont, 20); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "Generated on: " + calendar.toLocaleString(), 300, 770, 0); contentByte.endText(); contentByte.setLineWidth(1f); verticalPos -= spaceHeight; long startTime = startCal.getTimeInMillis(); long endTime = endCal.getTimeInMillis(); float maxChartValue = 0; float chartYAvg; BioSession tmpSession = sessionItems.get(0); int maxKeys = tmpSession.keyItemNames.length; // Loop through all of the the keys for (int key = 0; key < maxKeys; key++) { //Draw a border rect contentByte.setRGBColorStrokeF(0, 0, 0); contentByte.setLineWidth(1f); contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight); contentByte.stroke(); // Write band name contentByte.beginText(); contentByte.setFontAndSize(baseFont, 12); BioSession tmpSession1 = sessionItems.get(0); contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170, (verticalPos + (chartHeight / 2)) - 5, 0); contentByte.endText(); maxChartValue = 0; // First find the max Y for (BioSession session : sessionItems) { if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; if (chartYAvg > maxChartValue) maxChartValue = chartYAvg; } } float lastY = -1; float xIncrement = 0; if (sessionItems.size() > 0) { xIncrement = chartWidth / sessionItems.size(); } float yIncrement = 0; if (maxChartValue > 0) { yIncrement = chartHeight / maxChartValue; } float highValue = 0; int highTime = 0; float highY = 0; float highX = 0; int lowTime = 0; float lowY = 100; float lowX = chartWidth; float lowValue = maxChartValue; int lCount = 0; String keyName = ""; ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>(); // Loop through the session points of this key String rawYValues = ""; for (BioSession session : sessionItems) { keyName = session.keyItemNames[key]; if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; rawYValues += chartYAvg + ", "; if (lastY < 0) lastY = (float) chartYAvg; contentByte.setLineWidth(3f); contentByte.setRGBColorStrokeF(255, 0, 0); float graphXFrom = horizontalPos + (lCount * xIncrement); float graphYFrom = verticalPos + (lastY * yIncrement); float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement)); float graphYTo = verticalPos + (chartYAvg * yIncrement); // Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]"); // Draw the actual graph contentByte.moveTo(graphXFrom, graphYFrom); contentByte.lineTo(graphXTo, graphYTo); contentByte.stroke(); //Add regression Item ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement))); if (chartYAvg > highValue) { highValue = chartYAvg; highY = graphYTo; highX = graphXTo; highTime = (int) (session.time / 1000); } if (chartYAvg < lowValue) { lowValue = chartYAvg; lowY = graphYTo; lowX = graphXTo; lowTime = (int) (session.time / 1000); } lCount++; lastY = (float) chartYAvg; } // End if (session.time >= startTime && session.time <= endTime ) } // End for (BioSession session : sessionItems) //Draw high low dates if (highY != 0 && lowY != 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy"); String hDate = dateFormat.format(new Date((long) highTime * 1000L)); String lDate = dateFormat.format(new Date((long) lowTime * 1000L)); contentByte.beginText(); contentByte.setFontAndSize(baseFont, 8); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0); contentByte.endText(); } //Draw Regression Line RegressionResult regression = calculateRegression(ritems); contentByte.saveState(); contentByte.setRGBColorStrokeF(0, 0, 250); contentByte.setLineDash(3, 3, 0); contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept); contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept) + (float) (regression.slope * (chartWidth / xIncrement)))); contentByte.stroke(); contentByte.restoreState(); contentByte.setRGBColorStrokeF(0, 0, 0); // Log.e(TAG, keyName + ": [" + rawYValues + "]"); // Get ready for the next key (and series of database points ) verticalPos -= spaceHeight; if (verticalPos < 30) { document.newPage(); verticalPos = 780 - spaceHeight; } } // End for (int key = 0; key < maxKeys; key++) //document.add(new Paragraph("You can also write stuff directly tot he document like this!")); } catch (DocumentException de) { System.err.println(de.getMessage()); Log.e(TAG, de.toString()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); Log.e(TAG, ioe.toString()); } catch (Exception e) { System.err.println(e.getMessage()); Log.e(TAG, e.toString()); } // step 5: we close the document document.close(); fileExportCompleteHandler.sendEmptyMessage(EXPORT_SUCCESS); } }).start(); }
From source file:de.cuseb.bilderbuch.pdf.PdfController.java
License:Open Source License
@RequestMapping(value = "/pdf", method = RequestMethod.GET) public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) { try {// ww w.j ava2s .c o m PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest"); httpServletResponse.setContentType("application/pdf"); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream()); writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB); //document.addAuthor(pdfRequest.getAuthor()); //document.addTitle(pdfRequest.getTitle()); document.setPageSize( new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148))); document.open(); FontFactory.defaultEmbedding = true; FontFactory.register("IndieRock.ttf", "IndieRock"); Font font = FontFactory.getFont("IndieRock"); BaseFont baseFont = font.getBaseFont(); PdfContentByte cb = writer.getDirectContent(); Iterator<PdfPage> pages = pdfRequest.getPages().iterator(); while (pages.hasNext()) { PdfPage page = pages.next(); if (page.getImage() != null) { Image image = Image.getInstance(new URL(page.getImage().getUrl())); image.setDpi(300, 300); image.setAbsolutePosition(0f, 0f); image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight()); document.add(image); cb.saveState(); cb.beginText(); cb.setColorFill(Color.WHITE); cb.moveText(10f, 10f); cb.setFontAndSize(baseFont, 18); cb.showText(page.getSentence()); cb.endText(); cb.restoreState(); if (pages.hasNext()) { document.newPage(); } } } document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:fitnessmanagersystem.ExportPanel.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed Document document = new Document(PageSize.A2.rotate()); try {/*from w w w.j a va2 s . c o m*/ JFileChooser chooser = new JFileChooser("."); FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf"); chooser.setFileFilter(filter); chooser.showSaveDialog(this); String fileName = chooser.getSelectedFile().getPath(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Graphics2D g2 = cb.createGraphicsShapes(1500, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 1500, 500); jTable1_clients.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); } catch (FileNotFoundException | DocumentException e) { System.err.println(e.getMessage()); } document.close(); }
From source file:fitnessmanagersystem.ExportPanelProducts.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed Document document = new Document(PageSize.A2.rotate()); try {//from www . j a va2 s . c o m String FileDialog = null; // PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\DISHLIEV\\Desktop\\jTsdfb11wablwe.pdf")); JFileChooser chooser = new JFileChooser("."); FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf"); chooser.setFileFilter(filter); chooser.showSaveDialog(this); //chooser.setFileFilter(filter); // chooser.addChoosableFileFilter(filter); File file = chooser.getSelectedFile(); String fileName = chooser.getSelectedFile().getPath(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); // PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FileDialog+"C:\\Users\\DISHLIEV\\Desktop\\jTsdfb11wablwe.pdf")); /* FileDialog saveFileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE); saveFileDialog.setFile(""); saveFileDialog.setVisible(true); saveFileDialog.getDirectory(); try { dexceleporte exp = new dexceleporte(); exp.fillData(jTable1, new File(saveFileDialog.getDirectory()+saveFileDialog.getFile()+".xls")); } catch (Exception ex) { ex.printStackTrace(); } */ document.open(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); Graphics2D g2 = cb.createGraphicsShapes(1500, 500); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, 1500, 500); jTable12dfv.print(g2); g2.setClip(oldClip); g2.dispose(); cb.restoreState(); //} } catch (FileNotFoundException | DocumentException e) { System.err.println(e.getMessage()); } document.close(); }
From source file:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java
License:GNU General Public License
/** * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, * com.lowagie.text.Document)/*from w ww .ja va 2 s. c om*/ */ public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); // write the headertable table.setTotalWidth(document.right() - document.left()); table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 20, cb); // compose the footer String text = writer.getPageNumber() + " / "; float textSize = helv.getWidthPoint(text, 12); float textBase = document.bottom() - 49; cb.beginText(); cb.setFontAndSize(helv, 12); float adjust = helv.getWidthPoint("0", 12); cb.setTextMatrix(document.right() - textSize - adjust - 5, textBase); cb.showText(text); cb.endText(); cb.addTemplate(tpl, document.right() - adjust, textBase); cb.saveState(); // draw a Rectangle around the page cb.setLineWidth(1); cb.rectangle(20, 20, document.getPageSize().getWidth() - 40, document.getPageSize().getHeight() - 40); cb.stroke(); cb.restoreState(); }
From source file:fr.opensagres.odfdom.converter.pdf.internal.stylable.StylableTab.java
License:Open Source License
public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) { if (font.getBaseFont() != null && font.getSize() > 0.0 && leaderText.trim().length() > 0) { // create text to fit tab width float width = urx - llx; String txt = ""; while (true) { Chunk tmp = new Chunk(txt + leaderText, font); if (tmp.getWidthPoint() <= width) { txt += leaderText;/* w ww . j a v a 2 s . co m*/ } else { break; } } // compute x offset - as if tab were right aligned float xoffset = width - new Chunk(txt, font).getWidthPoint(); // compute y offset - use StylableParagraph mechanism Chunk tmp = StylableParagraph.createAdjustedChunk(txt, font, lineHeight, lineHeightProportional); float yoffset = tmp.getTextRise(); // draw canvas.saveState(); canvas.beginText(); canvas.setFontAndSize(font.getBaseFont(), font.getSize()); canvas.showTextAligned(Element.ALIGN_LEFT, txt, llx + xoffset, y + yoffset, 0.0f); canvas.endText(); canvas.restoreState(); } }
From source file:gui.TransHistory.java
public void Convertpdf() throws Exception { display();//from w w w .j av a 2s . c om 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 .ja v a2 s . 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:org.caisi.tickler.web.TicklerPrinter.java
License:Open Source License
public void footer() { PdfContentByte cb = writer.getDirectContent(); cb.saveState();//from w w w. j a va2 s . co m Date now = new Date(); String promoTxt = OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"); if (promoTxt == null) { promoTxt = new String(); } String strFooter = promoTxt + " " + formatter.format(now); float textBase = document.bottom(); cb.beginText(); cb.setFontAndSize(font.getBaseFont(), FONTSIZE); Rectangle page = document.getPageSize(); float width = page.getWidth(); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 20, 0); strFooter = "-" + writer.getPageNumber() + "-"; cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 10, 0); cb.endText(); cb.restoreState(); }
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 a v a2 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(); }