List of usage examples for com.itextpdf.text.pdf PdfContentByte createTemplate
public PdfTemplate createTemplate(final float width, final float height)
From source file:JT.java
public void createPdf(String filename) throws DocumentException, IOException { // step 1/*from w ww . j a va 2 s . c o m*/ Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 BaseFont bf = BaseFont.createFont("C:\\Windows\\Fonts\\vuTimes.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf, 15); document.open(); // step 4 String pa = "H? v tn : L Ng?c Long\n" + "MSSV : 20142659\n" + "?? ti : Xy dng chng trnh qun l th vin"; pa += "\n\nTr?ng ?i H?c Bch Khoa H Ni Cng Ha - X Hi - Ch Ngha - Vit Nam\n" + " Th vin T Quang Bu ?c Lp - T Do - Hnh Phc"; pa += "\n\n TM KIM S?CH THEO xxx"; document.add(new Paragraph(pa, font)); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(jTable1.getWidth(), jTable1.getHeight()); Graphics2D g2; g2 = tp.createGraphicsShapes(jTable1.getWidth(), jTable1.getHeight()); jTable1.print(g2); float x = 50, y = 300; g2.dispose(); cb.addTemplate(tp, x, y); // step 5 document.close(); }
From source file:Servlet3.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request// w ww . ja v a 2 s.c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { System.out.println("inside servlet"); String a = request.getParameter("countryf"); String c = request.getParameter("submit"); String b = request.getParameter("paramf"); //code added by Murugappan String CurentUID = request.getParameter("UIDvalue2f"); String URLRequest = request.getRequestURL().append('?').append(request.getQueryString()).toString(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy"); String date1 = cal.getTime().toString(); System.out.println("inside servlet"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:server"); //iserting data to UserActivity table Statement sthistoryinsert3 = con.createStatement(); String insertstring = "Insert into UserActivity values('" + CurentUID + "','" + date1 + "','Future Data Forecast','" + a + "','" + b + "','" + URLRequest + "')"; sthistoryinsert3.executeUpdate(insertstring); sthistoryinsert3.close(); System.out.println("\n Step 1"); Statement st = con.createStatement(); // Statement st2 = con.createStatement(); XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series = new XYSeries(b); String query = "SELECT [2000],[2012] FROM country where CountryName='" + a + "' AND SeriesName='" + b + "'"; System.out.println(query); ResultSet rs = st.executeQuery(query); if (rs == null) System.out.println("\n no rows "); else System.out.println("Rows present "); rs.next(); Double start = Double.parseDouble(rs.getString(1)); Double end = Double.parseDouble(rs.getString(2)); Double period = 13.0; Double growth = Math.pow((end / start), (1 / period)) - 1; System.out.println("growth percentage =" + growth); rs.close(); String query2 = "select [2011],[2012] from country where CountryName='" + a + "' AND SeriesName='" + b + "'"; rs = st.executeQuery(query2); rs.next(); series.add(2011, Double.parseDouble(rs.getString(1))); Double second = Double.parseDouble(rs.getString(2)); series.add(2012, second); Double growthvalue = second + (second * growth); series.add(2013, growthvalue); for (int i = 2014; i <= 2016; i++) { System.out.println("actual growth value = " + growthvalue); series.add((i++), (growthvalue + growthvalue * growth)); growthvalue = growthvalue + growthvalue * growth; } rs.close(); dataset.addSeries(series); DecimalFormat format_2Places = new DecimalFormat("0.00"); growth = growth * 100; growth = Double.valueOf(format_2Places.format(growth)); JFreeChart chart = ChartFactory.createXYLineChart( "Energy forecasting for " + a + " based on " + b + " with growth value estimated at " + growth + "% ", "Year", "Energy consumed in millions", dataset, PlotOrientation.VERTICAL, true, true, false); // JFreeChart chart1=ChartFactory.createLineChart("World population Growth","Year","population in millions",dataSet1,PlotOrientation.VERTICAL,true,true,false); ByteArrayOutputStream bos = new ByteArrayOutputStream(); chart.setBackgroundPaint(Color.white); final XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); plot.setDomainGridlinePaint(Color.black); plot.setRangeGridlinePaint(Color.black); final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setSeriesLinesVisible(2, false); renderer.setSeriesShapesVisible(2, false); plot.setRenderer(renderer); /* We have to insert this colored Pie Chart into the PDF file using iText now */ if (c.equals("View Graph in Browser")) { ChartUtilities.writeChartAsPNG(bos, chart, 700, 500); response.setContentType("image/png"); OutputStream out = new BufferedOutputStream(response.getOutputStream()); out.write(bos.toByteArray()); out.flush(); out.close(); } else { int width = 640; /* Width of our chart */ int height = 480; /* Height of our chart */ Document PieChart = new Document(new com.itextpdf.text.Rectangle(width, height)); java.util.Date date = new java.util.Date(); String chartname = "My_Colored_Chart" + date.getTime() + ".pdf"; PdfWriter writer = PdfWriter.getInstance(PieChart, new FileOutputStream(chartname)); PieChart.open(); /* Add some Metadata to identify document later */ PieChart.addTitle("How to color your Pie Chart and embed in a PDF file using iText"); PieChart.addAuthor("Thinktibits"); PieChart.addKeywords("iText,Color PieChart,JFreeChart,PDF,Example Tutorial"); PdfContentByte Add_Chart_Content = writer.getDirectContent(); PdfTemplate template_Chart_Holder = Add_Chart_Content.createTemplate(width, height); Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380); chart.draw(Graphics_Chart, Chart_Region); Graphics_Chart.dispose(); Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0); PieChart.close(); //PrintWriter out = response.getWriter(); //out.println("<!DOCTYPE html> <html> <body> <a href =file:///C:/apache-tomcat-8.0.12/bin/"+chartname+" download=newFileName> Download your file here </a> </body></html>"); PdfReader reader = new PdfReader(chartname); PdfStamper stamper = null; try { stamper = new PdfStamper(reader, bos); } catch (DocumentException e) { e.printStackTrace(); } try { stamper.close(); } catch (DocumentException e) { e.printStackTrace(); } // set some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setContentType("application/pdf"); response.setContentLength(bos.size()); OutputStream os = response.getOutputStream(); bos.writeTo(os); os.flush(); os.close(); } } catch (Exception i) { i.printStackTrace(); } }
From source file:by.bsuir.group172301.matskevich.tour.util.PDFCreator.java
public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName, int col1, int col2, double perc) { PdfWriter writer = null;//from w ww. j a v a 2 s .c o m Document document = new Document(); try { writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); Paragraph paragraph = new Paragraph(); // We add one empty line paragraph = new Paragraph("Results:"); paragraph.setAlignment(Element.ALIGN_CENTER); document.add(paragraph); paragraph = new Paragraph("Test before: " + col1); document.add(paragraph); paragraph = new Paragraph("Test after: " + col2); document.add(paragraph); paragraph = new Paragraph("Percentage: " + perc); document.add(paragraph); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 150, 250); } catch (Exception e) { e.printStackTrace(); } document.close(); }
From source file:ca.uwo.csd.cs2212.team02.MainWindow.java
/** * Export current page to PDF/*from w w w. java2s . co m*/ * * @param jpanel Panel to be exported to PDF */ public void createPDF(JLayeredPane jpanel) { playButtonSound(); com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(0, 0, jpanel.getWidth(), jpanel.getHeight()); Document doc = new Document(r); String filename = fileChooser(); if (filename != "INVALID") { try { PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename)); doc.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(PageSize.A4.getHeight() * 2, PageSize.A4.getWidth() * 2); Graphics2D g2; g2 = tp.createGraphics(jpanel.getWidth(), jpanel.getHeight(), new DefaultFontMapper()); jpanel.print(g2); g2.dispose(); cb.addTemplate(tp, 0, 0); PopUpWindow saveSuccess = new PopUpWindow(filename, "Save Successful!", 8); } catch (Exception e) { new PopUpWindow("Please try again.", "Error saving file"); } } doc.close(); }
From source file:canreg.client.analysis.Tools.java
License:Open Source License
public static void exportChartAsPDF(JFreeChart chart, Rectangle bounds, File file) throws IOException, DocumentException { System.out.println(file.getPath()); PdfWriter writer = null;// ww w. jav a 2s . com com.itextpdf.text.Document document = new com.itextpdf.text.Document(); document.addCreator("CanReg5"); document.addCreationDate(); writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(bounds.width, bounds.height); Graphics2D graphics2d = template.createGraphics(bounds.width, bounds.height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, bounds.width, bounds.height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); document.close(); }
From source file:cis_690_report.DynamicReporter.java
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed JFileChooser chooser = new JFileChooser(); int option = chooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { if (chooser.getSelectedFile() != null) { File3 = chooser.getSelectedFile().getAbsolutePath(); }//w w w. j a va 2s. c om try { br1 = new BufferedReader(new FileReader(f)); BufferedReader b1 = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException ex) { } String line = ""; bull1 = new String[number_of_rows - 1][]; int k = 0; BufferedReader br3 = null; try { br3 = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException ex) { } try { while ((line = br3.readLine()) != null) { // use comma as separator String Bull[] = line.split(","); if (k != 0) { System.out.println(Bull.length); bull1[k - 1] = new String[Bull.length]; for (int j = 0; j < Bull.length; j++) { bull1[k - 1][j] = Bull[j]; } } k++; } } catch (IOException ex) { } Document doc = new Document(); PdfWriter docWriter = null; DecimalFormat df = new DecimalFormat("0.00"); try { //special font sizes Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0)); Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6); Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); Font bfBold25 = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD); //file path docWriter = PdfWriter.getInstance(doc, new FileOutputStream(File3)); //document header attributes doc.addAuthor("Shubh Chopra"); doc.addCreationDate(); doc.addProducer(); doc.addCreator("Shubh Chopra"); doc.addTitle("BES"); doc.setPageSize(PageSize.LETTER.rotate()); //open document doc.open(); //create a paragraph Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n"); paragraph.setFont(bfBold25); paragraph.setAlignment(Element.ALIGN_CENTER); Image img = Image.getInstance("VETMED.png"); img.scaleToFit(300f, 150f); doc.add(paragraph); PdfPTable table1 = new PdfPTable(2); table1.setWidthPercentage(100); PdfPCell cell = new PdfPCell(img); cell.setBorder(PdfPCell.NO_BORDER); table1.addCell(cell); String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64] + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: " + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n"; table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT)); doc.add(table1); //specify column widths int temp = dlm2.size(); float[] columnWidths = new float[temp]; for (int x = 0; x < columnWidths.length; x++) { columnWidths[x] = 2f; } //create PDF table with the given widths PdfPTable table = new PdfPTable(columnWidths); // set table width a percentage of the page width table.setWidthPercentage(90f); DynamicReporter re; re = new DynamicReporter(); for (int i = 0; i < dlm2.size(); i++) { String[] parts = dlm2.get(i).toString().split(": "); String part2 = parts[1]; re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12); } table.setHeaderRows(1); //insert an empty row //create section heading by cell merging //just some random data to fill for (int x = 0; x < dlm3.size(); x++) { String str = dlm3.get(x).toString(); System.out.println(str); String[] parts = str.split(":"); String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; for (int i = 0; i < dlm2.getSize(); i++) for (int j = 0; j < header.length && j < bull1[row].length; j++) { String str1 = dlm2.get(i).toString(); String[] p1 = str1.split(": "); String p2 = p1[0]; if (p2.equals(header[j])) { re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12); } } // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12); } doc.add(table); if (jCheckBox2.isSelected()) { DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); for (int i = 0; i < dlm3.size(); i++) { String str = dlm3.get(i).toString(); System.out.println(str); String[] parts = str.split(":"); String part1 = parts[0]; String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; float total = (float) 0.0; for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (bull1[row][j].equals("")) { continue; } else { total += Integer.parseInt(bull1[row][j]); } } System.out.println(total); for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (!bull1[row][j].equals("")) { String[] Parts = header[j].split("_"); String Part2 = Parts[1]; dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1); } else { dataSet.setValue(0, "Percent", header[j]); } } } JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false); if (dlm3.size() > 12) { doc.newPage(); } PdfContentByte contentByte = docWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(325, 250); PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } if (jCheckBox1.isSelected()) { for (int i = 0; i < dlm3.size(); i++) { DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); String str = dlm3.get(i).toString(); System.out.println(str); String[] parts = str.split(":"); String part1 = parts[0]; String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; float total = (float) 0.0; for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (bull1[row][j].equals("")) { continue; } else { total += Integer.parseInt(bull1[row][j]); } } System.out.println(total); for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (!bull1[row][j].equals("")) { String[] Parts = header[j].split("_"); String Part2 = Parts[1]; dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2); } else { dataSet.setValue(0, "Percent", header[j]); } } JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1, "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false); if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) { doc.newPage(); } PdfContentByte contentByte = docWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(325, 250); PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); doc.newPage(); } } } catch (DocumentException dex) { dex.printStackTrace(); } catch (FileNotFoundException ex) { Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex); } finally { if (doc != null) { //close the document doc.close(); } if (docWriter != null) { //close the writer docWriter.close(); } } } // TODO add your handling code here: }
From source file:cis_690_report.DynamicReporter.java
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed // TODO add your handling code here: // build a controller SwingController controller = new SwingController(); // Build a SwingViewFactory configured with the controller SwingViewBuilder factory = new SwingViewBuilder(controller); // Use the factory to build a JPanel that is pre-configured //with a complete, active Viewer UI. JPanel viewerComponentPanel = factory.buildViewerPanel(); // add copy keyboard command ComponentKeyBinding.install(controller, viewerComponentPanel); // add interactive mouse link annotation support via callback controller.getDocumentViewController().setAnnotationCallback( new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController())); // Create a JFrame to display the panel in JFrame window = new JFrame("Using the Viewer Component"); window.getContentPane().add(viewerComponentPanel); window.pack();//from w w w . j a v a2s . com window.setVisible(true); String Path; Path = "C:/Users/Shubh Chopra/Documents/reporter.pdf"; try { br1 = new BufferedReader(new FileReader(f)); BufferedReader b1 = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException ex) { } String line = ""; bull1 = new String[number_of_rows - 1][]; int k = 0; BufferedReader br3 = null; try { br3 = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException ex) { } try { while ((line = br3.readLine()) != null) { // use comma as separator String Bull[] = line.split(","); if (k != 0) { System.out.println(Bull.length); bull1[k - 1] = new String[Bull.length]; for (int j = 0; j < Bull.length; j++) { bull1[k - 1][j] = Bull[j]; } } k++; } } catch (IOException ex) { } Document doc = new Document(); PdfWriter docWriter = null; DecimalFormat df = new DecimalFormat("0.00"); try { //special font sizes Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0)); Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6); Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); //file path docWriter = PdfWriter.getInstance(doc, new FileOutputStream(Path)); //document header attributes doc.addAuthor("Shubh Chopra"); doc.addCreationDate(); doc.addProducer(); doc.addCreator("Shubh Chopra"); doc.addTitle("BES"); doc.setPageSize(PageSize.LETTER.rotate()); //open document doc.open(); //create a paragraph Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n"); paragraph.setFont(bfBold20); paragraph.setAlignment(Element.ALIGN_CENTER); Image img = Image.getInstance("VETMED.png"); img.scaleToFit(300f, 150f); doc.add(paragraph); PdfPTable table1 = new PdfPTable(2); table1.setWidthPercentage(100); PdfPCell cell = new PdfPCell(img); cell.setBorder(PdfPCell.NO_BORDER); table1.addCell(cell); String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64] + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: " + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n"; table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT)); doc.add(table1); //specify column widths int temp = dlm2.size(); float[] columnWidths = new float[temp]; for (int x = 0; x < columnWidths.length; x++) { columnWidths[x] = 2f; } //create PDF table with the given widths PdfPTable table = new PdfPTable(columnWidths); // set table width a percentage of the page width table.setWidthPercentage(90f); DynamicReporter re; re = new DynamicReporter(); for (int i = 0; i < dlm2.size(); i++) { String[] parts = dlm2.get(i).toString().split(": "); String part2 = parts[1]; re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12); } table.setHeaderRows(1); //insert an empty row //create section heading by cell merging //just some random data to fill for (int x = 0; x < dlm3.size(); x++) { String str = dlm3.get(x).toString(); System.out.println(str); String[] parts = str.split(":"); String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; for (int i = 0; i < dlm2.getSize(); i++) for (int j = 0; j < header.length && j < bull1[row].length; j++) { String str1 = dlm2.get(i).toString(); String[] p1 = str1.split(": "); String p2 = p1[0]; if (p2.equals(header[j])) { re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12); } } // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12); } doc.add(table); if (jCheckBox2.isSelected()) { DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); for (int i = 0; i < dlm3.size(); i++) { String str = dlm3.get(i).toString(); System.out.println(str); String[] parts = str.split(":"); String part1 = parts[0]; String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; float total = (float) 0.0; for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (bull1[row][j].equals("")) { continue; } else { total += Integer.parseInt(bull1[row][j]); } } System.out.println(total); for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (!bull1[row][j].equals("")) { String[] Parts = header[j].split("_"); String Part2 = Parts[1]; dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1); } else { dataSet.setValue(0, "Percent", header[j]); } } } JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false); if (dlm3.size() > 12) { doc.newPage(); } PdfContentByte contentByte = docWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(325, 250); PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } if (jCheckBox1.isSelected()) { for (int i = 0; i < dlm3.size(); i++) { DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); String str = dlm3.get(i).toString(); System.out.println(str); String[] parts = str.split(":"); String part1 = parts[0]; String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; float total = (float) 0.0; for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (bull1[row][j].equals("")) { continue; } else { total += Integer.parseInt(bull1[row][j]); } } System.out.println(total); for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (!bull1[row][j].equals("")) { String[] Parts = header[j].split("_"); String Part2 = Parts[1]; dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2); } else { dataSet.setValue(0, "Percent", header[j]); } } JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1, "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false); if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) { doc.newPage(); } PdfContentByte contentByte = docWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(325, 250); PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); doc.newPage(); } } } catch (DocumentException dex) { dex.printStackTrace(); } catch (FileNotFoundException ex) { Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex); } finally { if (doc != null) { //close the document doc.close(); } if (docWriter != null) { //close the writer docWriter.close(); } } controller.openDocument(Path); }
From source file:cis_690_report.DynamicReporter.java
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed // TODO add your handling code here: // build a controller SwingController controller = new SwingController(); // Build a SwingViewFactory configured with the controller SwingViewBuilder factory = new SwingViewBuilder(controller); // Use the factory to build a JPanel that is pre-configured //with a complete, active Viewer UI. JPanel viewerComponentPanel = factory.buildViewerPanel(); // add copy keyboard command ComponentKeyBinding.install(controller, viewerComponentPanel); // add interactive mouse link annotation support via callback controller.getDocumentViewController().setAnnotationCallback( new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController())); // Create a JFrame to display the panel in JFrame window = new JFrame("Using the Viewer Component"); window.getContentPane().add(viewerComponentPanel); window.pack();/*from w w w.j a v a2s.c o m*/ window.setVisible(true); String Path; Path = "C:/Users/Shubh Chopra/Documents/reporter.pdf"; try { br1 = new BufferedReader(new FileReader(f)); BufferedReader b1 = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException ex) { } String line = ""; bull1 = new String[number_of_rows - 1][]; int k = 0; BufferedReader br3 = null; try { br3 = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException ex) { } try { while ((line = br3.readLine()) != null) { // use comma as separator String Bull[] = line.split(","); if (k != 0) { System.out.println(Bull.length); bull1[k - 1] = new String[Bull.length]; for (int j = 0; j < Bull.length; j++) { bull1[k - 1][j] = Bull[j]; } } k++; } } catch (IOException ex) { } Document doc = new Document(); PdfWriter docWriter = null; DecimalFormat df = new DecimalFormat("0.00"); try { //special font sizes Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD, new BaseColor(0, 0, 0)); Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 6); Font bfBold20 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); //file path docWriter = PdfWriter.getInstance(doc, new FileOutputStream(Path)); //document header attributes doc.addAuthor("Shubh Chopra"); doc.addCreationDate(); doc.addProducer(); doc.addCreator("Shubh Chopra"); doc.addTitle("BES"); doc.setPageSize(PageSize.LETTER.rotate()); //open document doc.open(); //create a paragraph Paragraph paragraph = new Paragraph("BULL EVALUATION\n\n"); paragraph.setFont(bfBold20); paragraph.setAlignment(Element.ALIGN_CENTER); Image img = Image.getInstance("VETMED.png"); img.scaleToFit(300f, 150f); doc.add(paragraph); PdfPTable table1 = new PdfPTable(2); table1.setWidthPercentage(100); PdfPCell cell = new PdfPCell(img); cell.setBorder(PdfPCell.NO_BORDER); table1.addCell(cell); String temp1 = "\tOwner: " + bull1[1][62] + " " + bull1[1][63] + "\n\n\tRanch: " + bull1[1][64] + "\n\n\tAddress: " + bull1[1][55] + "\n\n\tCity: " + bull1[1][57] + "\n\n\tState: " + bull1[1][60] + "\tZip: " + bull1[1][61] + "\n\n\tPhone: " + bull1[1][59] + "\n\n"; table1.addCell(getCell(temp1, PdfPCell.ALIGN_LEFT)); doc.add(table1); //specify column widths int temp = dlm2.size(); float[] columnWidths = new float[temp]; for (int x = 0; x < columnWidths.length; x++) { columnWidths[x] = 2f; } //create PDF table with the given widths PdfPTable table = new PdfPTable(columnWidths); // set table width a percentage of the page width table.setWidthPercentage(90f); DynamicReporter re; re = new DynamicReporter(); for (int i = 0; i < dlm2.size(); i++) { String[] parts = dlm2.get(i).toString().split(": "); String part2 = parts[1]; re.insertCell(table, newhead[Integer.parseInt(part2)], Element.ALIGN_CENTER, 1, bfBold12); } table.setHeaderRows(1); //insert an empty row //create section heading by cell merging //just some random data to fill for (int x = 0; x < dlm3.size(); x++) { String str = dlm3.get(x).toString(); System.out.println(str); String[] parts = str.split(":"); String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; for (int i = 0; i < dlm2.getSize(); i++) for (int j = 0; j < header.length && j < bull1[row].length; j++) { String str1 = dlm2.get(i).toString(); String[] p1 = str1.split(": "); String p2 = p1[0]; if (p2.equals(header[j])) { re.insertCell(table, bull1[row][j], Element.ALIGN_CENTER, 1, bf12); } } // re.insertCell(table, bull1[x][7] , Element.ALIGN_CENTER, 1, bf12); } doc.add(table); if (jCheckBox2.isSelected()) { DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); for (int i = 0; i < dlm3.size(); i++) { String str = dlm3.get(i).toString(); System.out.println(str); String[] parts = str.split(":"); String part1 = parts[0]; String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; float total = (float) 0.0; for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (bull1[row][j].equals("")) { continue; } else { total += Integer.parseInt(bull1[row][j]); } } System.out.println(total); for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (!bull1[row][j].equals("")) { String[] Parts = header[j].split("_"); String Part2 = Parts[1]; dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, Part2, part1); } else { dataSet.setValue(0, "Percent", header[j]); } } } JFreeChart chart = ChartFactory.createBarChart("Multi Bull Morphology Chart ", "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, true, true, false); if (dlm3.size() > 12) { doc.newPage(); } PdfContentByte contentByte = docWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(325, 250); PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } if (jCheckBox1.isSelected()) { for (int i = 0; i < dlm3.size(); i++) { DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); String str = dlm3.get(i).toString(); System.out.println(str); String[] parts = str.split(":"); String part1 = parts[0]; String part2 = parts[1]; System.out.println(part2); int row = Integer.parseInt(part2) - 1; float total = (float) 0.0; for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (bull1[row][j].equals("")) { continue; } else { total += Integer.parseInt(bull1[row][j]); } } System.out.println(total); for (int j = 77; j < header.length && j < bull1[row].length; j++) { if (!bull1[row][j].equals("")) { String[] Parts = header[j].split("_"); String Part2 = Parts[1]; dataSet.setValue((Integer.parseInt(bull1[row][j]) * 100) / total, "Percent", Part2); } else { dataSet.setValue(0, "Percent", header[j]); } } JFreeChart chart = ChartFactory.createBarChart("Single Bull Morphology Chart " + part1, "Morphology", "Percent", dataSet, PlotOrientation.VERTICAL, false, true, false); if ((dlm3.size() > 12 && i == 0) || jCheckBox2.isSelected()) { doc.newPage(); } PdfContentByte contentByte = docWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(325, 250); PdfGraphics2D graphics2d = new PdfGraphics2D(template, 325, 250); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 325, 250); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); doc.newPage(); } } } catch (DocumentException dex) { dex.printStackTrace(); } catch (FileNotFoundException ex) { Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Reporter.class.getName()).log(Level.SEVERE, null, ex); } finally { if (doc != null) { //close the document doc.close(); } if (docWriter != null) { //close the writer docWriter.close(); } } controller.openDocument(Path); }
From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java
License:Apache License
/** * /*from w w w . j av a2 s . co m*/ * chart * * @param section chart section ? * @param e chart element * @throws Exception */ public static void setChart(PdfWriter writer, Section section, Element e) throws Exception { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Element e1 : e.getChildren()) { if (!e1.getChild("column").getText().equals(FileType.DIRECTORY.toString()) && !e1.getChild("column").getText().equals(FileType.SUM.toString())) { dataset.setValue(Integer.parseInt(e1.getChild("value").getText()), e.getAttributeValue("title"), e1.getChild("column").getText()); } } JFreeChart chart = ChartFactory.createBarChart3D(e.getAttributeValue("title"), "", "", dataset, PlotOrientation.VERTICAL, false, true, false); CategoryPlot plot = chart.getCategoryPlot(); java.awt.Font labelFont = chart.getCategoryPlot().getDomainAxis().getLabelFont(); plot.getDomainAxis().setLabelFont(new java.awt.Font(labelFont.getName(), Font.NORMAL, 6)); plot.getDomainAxis().setTickLabelFont(new java.awt.Font(labelFont.getName(), Font.NORMAL, 6)); PdfContentByte cb = writer.getDirectContent(); PdfTemplate bar = cb.createTemplate(500, 150); Graphics2D g2d2 = new PdfGraphics2D(bar, 500, 150); Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, 500, 150); chart.draw(g2d2, r2d2); g2d2.dispose(); Image image = Image.getInstance(bar); image.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER); section.add(image); }
From source file:com.automaster.autoview.server.servlet.TextStateOperators.java
/** * Creates a PDF document.//from w ww.j av a2 s . c om * @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); Document document = new Document(rect, 30, 30, 30, 30); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 //PdfAcroForm canva = writer.getAcroForm(); BaseFont bf = BaseFont.createFont(); //canva.addMultiLineTextField("txtTeste", "texto de teste vamos ver se le quebra a linha", bf, 15, 300, 800, 100, 100); PdfContentByte canvas = writer.getDirectContent(); String text = "AWAY again"; String text1 = "TESTE Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto adriano"; canvas.beginText(); // line 1 canvas.setFontAndSize(bf, 16); canvas.moveText(36, 800); canvas.moveTextWithLeading(0, -24); canvas.setTextRise(10); canvas.showText(text); // line 2 canvas.setWordSpacing(20); canvas.newlineShowText(text); // line 3 canvas.setCharacterSpacing(10); canvas.newlineShowText(text); canvas.setWordSpacing(0); canvas.setCharacterSpacing(0); // line 4 canvas.setHorizontalScaling(50); canvas.newlineShowText(text); canvas.setHorizontalScaling(100); // line 5 canvas.newlineShowText(text); canvas.setTextRise(15); canvas.setFontAndSize(bf, 12); canvas.setColorFill(BaseColor.RED); canvas.showText("2"); canvas.setColorFill(GrayColor.GRAYBLACK); // line 6 canvas.setLeading(56); canvas.setMiterLimit(5); canvas.newlineShowText( "Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto" + text); canvas.setLeading(24); canvas.newlineText(); Paragraph paragraph = new Paragraph("teste"); PdfWriter pdfWriter = canvas.getPdfWriter(); PdfAcroForm pdfAcroForm = pdfWriter.getAcroForm(); //pdfAcroForm.addMultiLineTextField("txtTeste", "Changing the adriano leading: Rua alameda luis de sousa santos, N 52, castanhal, CEP: 68742-783, ao lado do posto", bf, 12, 30, 650, 550, 750); //pdfAcroForm.addHiddenField("txtTeste", text); PdfFormField pdfFormField = new PdfFormField(pdfWriter, 30, 650, 550, 750, null); pdfFormField.setFieldName("txtTeste"); pdfFormField.setValueAsString(text1); //TextField textField = new TextField(canvas.getPdfWriter(), new Rectangle(30, 650, 550, 750), "txtTest"); //textField.setText(text); pdfAcroForm.addFormField(pdfFormField); // line 7 PdfTextArray array = new PdfTextArray("A"); array.add(120); array.add("W"); array.add(120); array.add("A"); array.add(95); array.add("Y again"); canvas.showText(array); canvas.endText(); canvas.setColorFill(BaseColor.BLUE); canvas.beginText(); canvas.setTextMatrix(360, 770); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); canvas.beginText(); canvas.setTextMatrix(360, 730); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); canvas.beginText(); canvas.setTextMatrix(360, 690); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); canvas.beginText(); canvas.setTextMatrix(360, 650); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); PdfTemplate template = canvas.createTemplate(200, 36); template.setLineWidth(2); for (int i = 0; i < 6; i++) { template.moveTo(0, i * 6); template.lineTo(200, i * 6); } template.stroke(); canvas.saveState(); canvas.beginText(); canvas.setTextMatrix(360, 610); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); canvas.addTemplate(template, 360, 610); canvas.restoreState(); canvas.saveState(); canvas.beginText(); canvas.setTextMatrix(360, 570); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); canvas.addTemplate(template, 360, 570); canvas.restoreState(); canvas.saveState(); canvas.beginText(); canvas.setTextMatrix(360, 530); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); canvas.addTemplate(template, 360, 530); canvas.restoreState(); canvas.saveState(); canvas.beginText(); canvas.setTextMatrix(360, 490); canvas.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP); canvas.setFontAndSize(bf, 24); canvas.showText(text); canvas.endText(); canvas.addTemplate(template, 360, 490); canvas.restoreState(); // step 5 //document.add((Element) pdfAcroForm); document.close(); }