List of usage examples for com.itextpdf.text.pdf PdfContentByte addTemplate
public void addTemplate(final PdfTemplate template, final double x, final double y)
From source file:JT.java
public void createPdf(String filename) throws DocumentException, IOException { // step 1//from w w w. ja v a 2 s . c om 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//from ww w.java2 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:adams.flow.transformer.pdfproclet.PDFGenerator.java
License:Open Source License
/** * Opens the document for appending content. * * @throws Exception if opening fails/*from w w w. j av a 2s. c o m*/ */ public void append() throws Exception { PdfReader reader; File tmpFile; int i; PdfImportedPage page; PdfContentByte cb; if (isLoggingEnabled()) getLogger().info("Appending document: " + m_Output); resetState(); tmpFile = TempUtils.createTempFile("adams", ".pdf"); if (tmpFile.exists()) { if (!tmpFile.delete()) throw new IllegalStateException("Failed to delete temporary PDF file '" + tmpFile + "'!"); } if (!FileUtils.copy(m_Output, tmpFile)) throw new IllegalStateException( "Failed to move original PDF file '" + m_Output + "' to '" + tmpFile + "'!"); reader = new PdfReader(tmpFile.getAbsolutePath()); if (reader.getNumberOfPages() > 0) { m_Document = new Document(reader.getPageSize(1)); } else { if (m_PageOrientation == PageOrientation.PORTRAIT) m_Document = new Document(determinePageSize()); else m_Document = new Document(determinePageSize().rotate()); } m_Stream = new FileOutputStream(m_Output.getAbsoluteFile()); m_Writer = PdfWriter.getInstance(m_Document, m_Stream); m_Document.open(); m_Document.addCreationDate(); m_Document.addCreator(Environment.getInstance().getProject()); m_Document.addAuthor(System.getProperty("user.name")); m_State = new DocumentState(); cb = m_Writer.getDirectContent(); for (i = 0; i < reader.getNumberOfPages(); i++) { page = m_Writer.getImportedPage(reader, i + 1); m_Document.newPage(); cb.addTemplate(page, 0, 0); } }
From source file:book.pdftemplates.FillTemplateHelper.java
@Override public void onEndPage(PdfWriter writer, Document document) { PdfContentByte canvas = writer.getDirectContentUnder(); // background canvas.addTemplate(background, 0, 0); try {// www.j a v a2 s . c o m // date ColumnText ct = new ColumnText(canvas); ct.setSimpleColumn(date); ct.addText(new Chunk(today, font)); ct.go(); // footer (page X of Y) ct.setSimpleColumn(footer); ct.addText(new Chunk("page " + writer.getPageNumber(), font)); ct.addText(new Chunk(Image.getInstance(total), 0, 0)); ct.go(); // from address ct.setSimpleColumn(from); ct.addElement(new Paragraph(sender, font)); ct.go(); // to address ct.setSimpleColumn(to); ct.addElement(new Paragraph(receiver, font)); ct.go(); } catch (DocumentException e) { // can never happen, but if it does, we want to know! throw new ExceptionConverter(e); } }
From source file:br.jus.jfpr.Divisor1.java
/** * Divide um arquivo inicialmente em 2, testa se o tamanho que todos * arquivos ficaram dentro do limite, se no ficaram apaga tudo e recomea * dividindo por, 3, 4, 5, etc. at que todos arquivo fiquem dentro do * limite/* w w w . ja v a 2 s .c o m*/ * * @param arquivoEntrada O arquivo que ser dividido * @param arquivoSaida O nome do arquivo que ser criado * @param tamArqSel Tamanho selecionado que devero ficar os arquivos * divididos * @return String informativa do resultado */ public static String dividePDF(File arquivoEntrada, String arquivoSaida, int tamArqSel) { int daPagina = 1; int paraPagina; int tamInicial; // FileOutputStream arquivoSair = null; String MensagemErro = "ok"; int fatorDivisao = 2; //Incialmente dividir em 2 arquivoSaida = arquivoSaida.substring(0, arquivoSaida.indexOf('.')) + "-divido"; //PAra definir o nome do arquivo de sada try { PdfReader PdfDeEntrada = new PdfReader(arquivoEntrada.getAbsolutePath()); //Para ler o arquivo de entrada final int totalPaginas = PdfDeEntrada.getNumberOfPages(); //Verifica o total de pginas tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Define o tamanho (em pginas) do 1 arquivo e em quanto dever incrementar(sero o mesmo) PdfImportedPage pagina; int i = 1; //Contador simples while (i <= fatorDivisao && totalPaginas > fatorDivisao) { //Enquanto no fizer todas as divises Document documento = new Document(); FileOutputStream arquivoSair = new FileOutputStream(arquivoSaida + "-" + i + ".pdf"); //Cria o arquivo, vazio PdfWriter writer = PdfWriter.getInstance(documento, arquivoSair); // documento.open(); PdfContentByte PContentByte = writer.getDirectContent(); while (daPagina <= paraPagina) { documento.newPage(); //Aloca uma nova pginA pagina = writer.getImportedPage(PdfDeEntrada, daPagina); //Seleciona uma pgina especfica. indicada pelo contador PContentByte.addTemplate(pagina, 0, 0); //Adiciona a pagina ao contedo daPagina++; //Contador simples } arquivoSair.flush(); documento.close(); //Grava o arquivo de sada arquivoSair.close(); File arquivoDest = new File(arquivoSaida + "-" + i + ".pdf"); if (arquivoDest.length() > tamArqSel) { // O tamanho do arquivo de destino ficou maior do que deveria delete(arquivoSaida, i); //Chamar a funo para deletar todos arquivos at a chave i daPagina = i = 1; //Para recomear tudo de novo fatorDivisao++; //Se um arquivo ficou maior, ento deve aumentar a diviso tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Para recomear tudo de novo } else { i++; //Continua a divisao if (i == fatorDivisao) { //Ou seja, chegou a ultima divisao paraPagina = totalPaginas; //O ultimo arquivo conter mais pginas } else { paraPagina += tamInicial; //Cada arquivo ter o mesmo nmero de pginas//Incrementa sempre o tamanho inicial } } } } catch (IOException | DocumentException e) { System.err.println(e.getMessage()); MensagemErro = e.getMessage(); } return MensagemErro; }
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;/* ww w . jav 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// w ww . ja v a2 s .c o 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;/*w ww . java2s . co m*/ 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(); }//from w w w.j a v a2 s. com 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();// w w w.ja v a2 s. c om 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); }