public static void exportImg() { Document document = null; try { // BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", // BaseFont.NOT_EMBEDDED);// 设置中文字体 // Font headFont = new Font(bfChinese, 10, Font.NORMAL);// 设置字体大小 document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("D:/test/img.pdf")); // 设定文档的作者 document.addAuthor("林计钦"); // 测试无效 document.open(); document.add(new Paragraph("你好,Img!")); // 读取一个图片 Image image = Image.getInstance("D:/test/1.jpg"); // 插入一个图片 document.add(image); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (document != null) { document.close(); } } }
/** * Method to export charts as PDF files using the defined path. * * @param path The filename and absolute path. * @param chart The JFreeChart object. * @param width The width of the PDF file. * @param height The height of the PDF file. * @param mapper The font mapper for the PDF file. * @param title The title of the PDF file. * @throws IOException If writing a PDF file fails. */ @SuppressWarnings("deprecation") public static void exportPdf( String path, JFreeChart chart, int width, int height, FontMapper mapper, String title) throws IOException { File file = new File(path); FileOutputStream pdfStream = new FileOutputStream(file); BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream); Rectangle pagesize = new Rectangle(width, height); Document document = new Document(); document.setPageSize(pagesize); document.setMargins(50, 50, 50, 50); document.addAuthor("OMSimulationTool"); document.addSubject(title); try { PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput); document.open(); PdfContentByte contentByte = pdfWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D g2D = template.createGraphics(width, height, mapper); Double r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2D, r2D); g2D.dispose(); contentByte.addTemplate(template, 0, 0); } catch (DocumentException de) { JOptionPane.showMessageDialog( null, "Failed to write PDF document.\n" + de.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); de.printStackTrace(); } document.close(); }
private void exportGraphToPdf(mxGraph graph, String filename) { Rectangle bounds = new Rectangle(trackScheme.getGUI().graphComponent.getViewport().getViewSize()); // step 1 com.itextpdf.text.Rectangle pageSize = new com.itextpdf.text.Rectangle(bounds.x, bounds.y, bounds.width, bounds.height); com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize); // step 2 PdfWriter writer = null; Graphics2D g2 = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 PdfContentByte canvas = writer.getDirectContent(); g2 = canvas.createGraphics(pageSize.getWidth(), pageSize.getHeight()); trackScheme.getGUI().graphComponent.getViewport().paintComponents(g2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } finally { g2.dispose(); document.close(); } }
public boolean convertToPDF() throws MalformedURLException, IOException { JFileChooser filechooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(".pdf", "pdf"); filechooser.setFileFilter(filter); int result = filechooser.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File saveFile = filechooser.getSelectedFile(); Document pdfDocument = new Document(); PdfPTable table = new PdfPTable(1); com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(780, 580); Image slideImage = null; PdfWriter pdfWriter; try { pdfWriter = PdfWriter.getInstance( pdfDocument, new FileOutputStream(saveFile.getAbsolutePath() + ".pdf")); pdfWriter.open(); pdfDocument.open(); // pdfDocument.setPageSize(r); for (int i = 0; i < canvas.length; i++) { BufferedImage tempimg = new BufferedImage(720, 540, BufferedImage.TYPE_INT_ARGB); Graphics2D temgraphics = (Graphics2D) tempimg.getGraphics(); temgraphics.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); temgraphics.drawImage(img[i], 0, 0, 720, 540, null); temgraphics.drawImage(canvas[i], 0, 0, 720, 540, null); // slideImage = Image.getInstance(img[i], null); slideImage = com.itextpdf.text.Image.getInstance(tempimg, null); // table.addCell(new PdfPCell(slideImage, true)); // Image imagex = com.itextpdf.text.Image.getInstance(""); pdfDocument.setPageSize(r); pdfDocument.newPage(); pdfDocument.add(slideImage); } pdfDocument.close(); pdfWriter.close(); System.out.println("Powerpoint file converted to PDF successfully"); return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { return false; } return false; }
private void generar(String nombreArchivo) { Document documento = new Document(); try { PdfWriter.getInstance(documento, new FileOutputStream(nombreArchivo)); documento.open(); documento.add(new Paragraph(cabecera + mensaje)); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } documento.close(); }
public void process(ObjectIO input, ObjectIO output) { try { // OJO pasarle el idemisor String idemisor = "1"; recuperaInput(input); Rectangle pageSize = new Rectangle(PageSize.A4); // pageSize.setBackgroundColor(Color.TRANSLUCENT); pageSize.rotate(); documento = new Document(pageSize); System.out.println("WIDTH " + documento.getPageSize().getWidth()); System.out.println("HEIGHT " + documento.getPageSize().getHeight()); namefile = "BarCode_" + idemisor + "_codigoBARRAS.pdf"; filecrea = "C://DATOS//LRA//tmp//" + namefile; // filecrea = PropiedadesJLet.getInstance().getProperty("path.gen.recibo") +"emisor_"+ // idemisor +"/"+ namefile; System.out.println( "***************************Se va a crear este codigo de barras: " + filecrea); writer = PdfWriter.getInstance(documento, new FileOutputStream(filecrea)); documento.open(); pintaCodigoBarras(); absText(writer, texto1xx, xpostex1, ypostex1, 8); absText(writer, texto2xx, xpostex2, ypostex2, 8); try { output.setValue("idemisor", idemisor); output.setValue("filecrea", namefile); output.setValue("txmensaj", "Generacion Ok - "); } catch (Exception e) { e.printStackTrace(); } } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } finally { documento.close(); } }
/** * @throws IOException * @throws DocumentException * @since 5.0.6 */ public void simpleSnippet() throws IOException, DocumentException { HashMap<String, Object> providers = new HashMap<String, Object>(); List<Element> parseToList = HTMLWorker.parseToList(new StringReader(snippet.toString()), null, providers); Document d = new Document(PageSize.A4); PdfWriter.getInstance(d, new FileOutputStream(new File("./test.pdf"))); d.open(); for (Element e : parseToList) { try { d.add(e); } catch (DocumentException e1) { e1.printStackTrace(); fail("unable to add element " + e); } } d.close(); }
public static void main(String[] args) { Document document = new Document(); // 创建文档对象 try { PdfWriter.getInstance(document, new FileOutputStream("C:\\明日科技简介.pdf")); // 关联文档对象与输出流 document.open(); // 打开文档 document.add(new Paragraph("Generalize")); // 向文档中添加内容 document.add( new Paragraph( "Welcome to GuangZhou!", FontFactory.getFont(FontFactory.HELVETICA, 15, Font.UNDERLINE))); // 向文档中添加内容 document.close(); // 关闭文档 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
private StreamResource getPDFStream(final List<ChangeRecord> records) { StreamResource.StreamSource source = (StreamResource.StreamSource) () -> { try { PdfUtils pdfCreator = new PdfUtils(); pdfCreator.open(); pdfCreator.exportChanges(records); pdfCreator.close(); return new ByteArrayInputStream(pdfCreator.getOutputStream().toByteArray()); } catch (DocumentException e) { e.printStackTrace(); } return null; }; return new StreamResource(source, createReportName("pdf")); }
public static void main(String args[]) { String jsonFilename = args[0]; String inputFilename = args[1]; String outputFilename = args[2]; try { BufferedReader jsonReader = new BufferedReader(new FileReader(jsonFilename)); FileOutputStream outputStream = new FileOutputStream(outputFilename); PdfReader reader = new PdfReader(inputFilename); PdfStamper stamper = new PdfStamper(reader, outputStream); StringBuffer jsonData = new StringBuffer(); String currentLine; // Read in all the JSON data while ((currentLine = jsonReader.readLine()) != null) { jsonData.append(currentLine); } // Convert JSON string into an accessible JSON object JSONObject jsonObj = new JSONObject(jsonData.toString()); Iterator fieldIterator = jsonObj.keys(); AcroFields fields = stamper.getAcroFields(); // Set all the fields based on the JSON config while (fieldIterator.hasNext()) { String fieldName = (String) fieldIterator.next(); String fieldValue = (String) jsonObj.getString(fieldName); fields.setField(fieldName, fieldValue); } // Flatten and save the PDF stamper.setFormFlattening(true); stamper.close(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); } catch (DocumentException e) { System.err.println("DocumentException: " + e.getMessage()); } catch (JSONException e) { System.err.println("JSONException: " + e.getMessage()); } }
public void absText( PdfWriter twriter, String text, float ypostex12, float ypostex22, int fontsize) { try { PdfContentByte cb = twriter.getDirectContent(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.saveState(); cb.beginText(); cb.moveText(ypostex12, ypostex22); cb.setFontAndSize(bf, fontsize); cb.setColorFill(new BaseColor(0, 0, 0)); cb.showText(text); cb.endText(); cb.restoreState(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // Get the text that will be added to the PDF String text = request.getParameter("text"); if (text == null || text.trim().length() == 0) { text = "You didn't enter any text."; } // step 1 Document document = new Document(); // step 2 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); // step 3 document.open(); // step 4 document.add( new Paragraph( String.format( "You have submitted the following text using the %s method:", request.getMethod()))); document.add(new Paragraph(text)); // step 5 document.close(); // setting some response headers response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); // setting the content type response.setContentType("application/pdf"); // the contentlength response.setContentLength(baos.size()); // write ByteArrayOutputStream to the ServletOutputStream OutputStream os = response.getOutputStream(); baos.writeTo(os); os.flush(); os.close(); } catch (DocumentException e) { throw new IOException(e.getMessage()); } }
public static void main(String[] args) { Document document = new Document(); // 打开文档 try { PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream("c:\\使用PdfGraphics2D绘制图片.pdf")); // 关联文档与输出流 document.open(); // 打开文档 PdfContentByte cb = writer.getDirectContent(); // 获取文档内容 PdfGraphics2D g = (PdfGraphics2D) cb.createGraphics(700, 800); // 创建PdfGraphics2D对象 BufferedImage image = ImageIO.read(new File("image/picture.jpg")); // 获取图片 g.drawImage(image, 50, 10, null); // 绘制图片 g.dispose(); // 部署 cb.stroke(); // 确认绘制的内容 document.close(); // 关闭文档 } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
public void downLoadFirst() { String url = null; String filename = null; if (downpdf) { doc = new Document(PageSize.A4); try { BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); fontChinese = new Font(bf, 13, Font.NORMAL); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 按列表顺序保存资源 for (int i = 0; i < vDownLoad.size(); i++) { url = (String) vDownLoad.get(i); filename = (String) vFileList.get(i); doc = new Document(PageSize.A4); try { GetLzTianya(url, filename); } catch (IOException err) { if (DEBUG) { bug = 1; title = null; author = null; link = null; mark = 0; title_mark = 0; pages = 1; } } } if (DEBUG) { vDownLoad = new Vector<String>(); vFileList = new Vector<String>(); } }
public static void notifyChange(Inspeccion inspeccion, Integer action) { try { MailService service = MailServiceFactory.getMailService(); MailService.Message msg = new MailService.Message(); msg.setSender("*****@*****.**"); // Segun el tipo de accion que se ejecuto cambian los destinatarios. InspeccionMailStrategy strategy = new ObservadoStrategy().getStrategy(action); strategy.exec(inspeccion, msg); msg.setSubject( "Detalle de inspeccion n°: " + inspeccion.getId() + " estado:" + inspeccion.getState().toString()); // msg.setContent(InspeccionHMTL.getInspeccionHTML(inspeccion),"text/html"); // http://127.0.0.1:8888/createpdfservlet CustomWorker cworker = new CustomWorker(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { cworker.exec(bos, new StringReader(InspeccionHMTL.getInspeccionHTML(inspeccion))); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } msg.setTextBody("Detalle de inspeccion Adjunto en formato PDF"); Attachment a = new Attachment("reporte.pdf", bos.toByteArray()); msg.setAttachments(a); service.send(msg); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void Write(String words) { if (downpdf) { String c_line = System.getProperty("line.separator"); try { if (words.equals(c_line)) { Paragraph cline = new Paragraph(" "); doc.add(cline); } else { Paragraph pf = new Paragraph(words, fontChinese); doc.add(pf); } } catch (DocumentException e) { e.printStackTrace(); } } else { try { writer.write(words); } catch (IOException e) { e.printStackTrace(); } } }
private void generateInvoicePDFByExamination( Examination examination, HttpServletResponse response) throws FileNotFoundException { Document document = new Document(); response.setHeader("Accept-ranges", "bytes"); response.setContentType("application/pdf"); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Content-Description", "File Transfer"); response.setHeader("Content-Transfer-Encoding:", "binary"); try { PdfWriter.getInstance(document, response.getOutputStream()); document.open(); addMetaData(document); addTitlePage(document, examination); document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Document document = new Document(PageSize.A4); try { PdfWriter.getInstance(document, resp.getOutputStream()); document.open(); Image image = Image.getInstance("img/logo9999.jpg"); document.add(image); document.add(new Paragraph("Gerando Pdf")); } catch (DocumentException de) { de.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { document.close(); } }
public void export( HttpServletResponse response, Long id, List<DemandeValidationConsoTempsAccPers> dctap) { try { Connection con = ds.getConnection(); Statement select = con.createStatement(); ResultSet rs = select.executeQuery("SELECT user.* FROM user where id = " + id); Document document = new Document(PageSize.A4); try { OutputStream out = response.getOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, out); writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage | PdfWriter.PageModeUseThumbs); document.open(); rs.last(); String eleve = "Nom : " + rs.getString("nom"); eleve += "\nPrénom : " + rs.getString("prenom"); int idClasse = rs.getInt("idClasse"); rs.beforeFirst(); ResultSet rs2 = select.executeQuery("SELECT classe.* from classe where id = " + idClasse); rs2.last(); eleve += "\nClasse : " + rs2.getString("libelle") + "\n\n\n"; rs2.beforeFirst(); Paragraph paragraph = new Paragraph(eleve); paragraph.setAlignment(Element.ALIGN_LEFT); document.add(paragraph); com.itextpdf.text.Font fontbold = FontFactory.getFont("Times-Roman", 18, Font.BOLD); paragraph = new Paragraph("Les demandes de validations\n\n", fontbold); paragraph.setAlignment(Element.ALIGN_CENTER); document.add(paragraph); int timeTT = 0, timeVal = 0, timeAtt = 0, timeRef = 0; for (int i = 0; i < dctap.size(); i++) { timeTT += dctap.get(i).getMinutes(); if (dctap.get(i).getEtat() == 1 || dctap.get(i).getEtat() == 32) { timeVal += dctap.get(i).getMinutes(); } else if (dctap.get(i).getEtat() == 2 || dctap.get(i).getEtat() == 8 || dctap.get(i).getEtat() == 64) { timeRef += dctap.get(i).getMinutes(); } else if (dctap.get(i).getEtat() == 0 || dctap.get(i).getEtat() == 4 || dctap.get(i).getEtat() > 1023) { timeAtt += dctap.get(i).getMinutes(); } } double timeTTpercent = timeVal, timeValPercent = timeVal, timeAttPercent = timeAtt, timeRefPercent = timeRef; timeTTpercent = Math.round((timeTTpercent / (72 * 60) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2); timeValPercent = Math.round(((timeValPercent / timeTT) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2); timeAttPercent = Math.round(((timeAttPercent / timeTT) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2); timeRefPercent = Math.round(((timeRefPercent / timeTT) * 100) * Math.pow(10.0, 2)) / Math.pow(10.0, 2); PdfPTable table = new PdfPTable(4); PdfPCell c1 = new PdfPCell( new Phrase( "Temps total effectué (72h)", FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD))); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(7); table.addCell(c1); c1 = new PdfPCell( new Phrase( "Temps total validé", FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD))); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(7); table.addCell(c1); c1 = new PdfPCell( new Phrase( "Temps total en attente", FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD))); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(7); table.addCell(c1); c1 = new PdfPCell( new Phrase( "Temps total refusé", FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, com.itextpdf.text.Font.BOLD))); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(7); table.addCell(c1); table.setHeaderRows(1); c1 = new PdfPCell( new Phrase((timeTT / 60 - (timeTT % 60 / 60)) + "h " + (timeTT % 60) + "min")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); c1 = new PdfPCell( new Phrase((timeVal / 60 - (timeVal % 60 / 60)) + "h " + (timeVal % 60) + "min")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); c1 = new PdfPCell( new Phrase((timeAtt / 60 - (timeAtt % 60 / 60)) + "h " + (timeAtt % 60) + "min")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); c1 = new PdfPCell( new Phrase((timeRef / 60 - (timeRef % 60 / 60)) + "h " + (timeRef % 60) + "min")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); c1 = new PdfPCell(new Phrase(timeTTpercent + "%")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); c1 = new PdfPCell(new Phrase(timeValPercent + "%")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); c1 = new PdfPCell(new Phrase(timeAttPercent + "%")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); c1 = new PdfPCell(new Phrase(timeRefPercent + "%")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setPaddingBottom(4); table.addCell(c1); document.add(table); } catch (DocumentException de) { de.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } document.close(); } catch (SQLException e) { e.printStackTrace(); } }
public static void main(String[] args) { Document document = new Document(PageSize.A4); try { PdfWriter.getInstance(document, new FileOutputStream("Relatorio.pdf")); document.open(); Font font = new Font(FontFamily.TIMES_ROMAN, 7, Font.BOLD); Paragraph cabecalho = new Paragraph("Relatório UniChef"); Paragraph sabor = new Paragraph("Sabor do Prato", font); Paragraph aparencia = new Paragraph("Aparência do Prato", font); Paragraph criatividadePrato = new Paragraph("Criatividade do Prato", font); Paragraph criatividadeBarraca = new Paragraph("Criatividade da Barraca", font); cabecalho.setAlignment(Element.ALIGN_CENTER); document.add(cabecalho); document.add(new Paragraph(" ")); SubEvento subEvento = new SubEventoDAO().buscar(6); PdfPTable pTable = new PdfPTable(4); PdfPCell cellCabecalho = new PdfPCell( new Paragraph( "Evento: " + subEvento.getEvento().getNome() + " Barraca: " + subEvento.getNome())); PdfPCell cellSabor = new PdfPCell(sabor); PdfPCell cellAparencia = new PdfPCell(aparencia); PdfPCell cellCriatividadePrato = new PdfPCell(criatividadePrato); PdfPCell cellCriatividadeBarraca = new PdfPCell(criatividadeBarraca); cellCabecalho.setHorizontalAlignment(Element.ALIGN_CENTER); cellSabor.setHorizontalAlignment(Element.ALIGN_CENTER); cellAparencia.setHorizontalAlignment(Element.ALIGN_CENTER); cellCriatividadePrato.setHorizontalAlignment(Element.ALIGN_CENTER); cellCriatividadeBarraca.setHorizontalAlignment(Element.ALIGN_CENTER); cellCabecalho.setColspan(4); pTable.addCell(cellCabecalho); pTable.addCell(cellSabor); pTable.addCell(cellAparencia); pTable.addCell(cellCriatividadePrato); pTable.addCell(cellCriatividadeBarraca); List<Avaliacao> avaliacoes = new AvaliacaoDAO().avaliacaoSubEvento(6); for (Avaliacao avaliacao : avaliacoes) { pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getSabor().toString()))); pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getAparencia().toString()))); pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getCriatividade().toString()))); pTable.addCell(new PdfPCell(new Paragraph(avaliacao.getCriatividadeBarraca().toString()))); } document.add(pTable); } catch (DocumentException de) { de.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { document.close(); } }
private AlfrescoRuntimeException signFile( final NodeRef nodeRefToSign, final DigitalSigningDTO signingDTO, final File alfTempDir, final String alias, final KeyStore ks, final PrivateKey key, final Certificate[] chain) { final String fileNameToSign = fileFolderService.getFileInfo(nodeRefToSign).getName(); File fileConverted = null; File tempDir = null; try { ContentReader fileToSignContentReader = getReader(nodeRefToSign); if (fileToSignContentReader != null) { String newName = null; // Check if document is PDF or transform it if (!MimetypeMap.MIMETYPE_PDF.equals(fileToSignContentReader.getMimetype())) { // Transform document in PDF document final ContentTransformer tranformer = contentTransformerRegistry.getTransformer( fileToSignContentReader.getMimetype(), fileToSignContentReader.getSize(), MimetypeMap.MIMETYPE_PDF, new TransformationOptions()); if (tranformer != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); fileConverted = new File(tempDir, fileNameToSign + "_" + System.currentTimeMillis() + ".pdf"); if (fileConverted != null) { final ContentWriter newDoc = new FileContentWriter(fileConverted); if (newDoc != null) { newDoc.setMimetype(MimetypeMap.MIMETYPE_PDF); tranformer.transform(fileToSignContentReader, newDoc); fileToSignContentReader = new FileContentReader(fileConverted); final String originalName = (String) nodeService.getProperty(nodeRefToSign, ContentModel.PROP_NAME); newName = originalName.substring(0, originalName.lastIndexOf(".")) + ".pdf"; } } } } else { log.error( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); } } // Convert PDF in PDF/A format final File pdfAFile = convertPdfToPdfA(fileToSignContentReader.getContentInputStream()); final PdfReader reader = new PdfReader(new FileInputStream(pdfAFile)); if (nodeRefToSign != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); final File file = new File(tempDir, fileNameToSign); if (file != null) { final FileOutputStream fout = new FileOutputStream(file); final PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); if (stp != null) { final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (sap != null) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason(signingDTO.getSignReason()); sap.setLocation(signingDTO.getSignLocation()); sap.setContact(signingDTO.getSignContact()); sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); sap.setImageScale(1); // digital signature if (signingDTO.getSigningField() != null && !signingDTO.getSigningField().trim().equalsIgnoreCase("")) { Image img = null; if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); final AcroFields af = reader.getAcroFields(); if (af != null) { final List<FieldPosition> positions = af.getFieldPositions(signingDTO.getSigningField()); if (positions != null && positions.size() > 0 && positions.get(0) != null && positions.get(0).position != null) { final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, Float.valueOf(positions.get(0).position.getWidth()).intValue(), Float.valueOf(positions.get(0).position.getHeight()).intValue()); img = Image.getInstance(newImg, null); } else { log.error( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); } } if (img == null) { img = Image.getInstance( ImageIO.read(imageContentReader.getContentInputStream()), null); } sap.setImage(img); } sap.setVisibleSignature(signingDTO.getSigningField()); } else { int pageToSign = 1; if (DigitalSigningDTO.PAGE_LAST.equalsIgnoreCase( signingDTO.getPages().trim())) { pageToSign = reader.getNumberOfPages(); } else if (DigitalSigningDTO.PAGE_SPECIFIC.equalsIgnoreCase( signingDTO.getPages().trim())) { if (signingDTO.getPageNumber() > 0 && signingDTO.getPageNumber() <= reader.getNumberOfPages()) { pageToSign = signingDTO.getPageNumber(); } else { throw new AlfrescoRuntimeException("Page number is out of bound."); } } if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); // Resize image final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, signingDTO.getSignWidth(), signingDTO.getSignHeight()); final Image img = Image.getInstance(newImg, null); sap.setImage(img); } if (signingDTO.getPosition() != null && !DigitalSigningDTO.POSITION_CUSTOM.equalsIgnoreCase( signingDTO.getPosition().trim())) { final Rectangle pageRect = reader.getPageSizeWithRotation(1); sap.setVisibleSignature( positionSignature( signingDTO.getPosition(), pageRect, signingDTO.getSignWidth(), signingDTO.getSignHeight(), signingDTO.getxMargin(), signingDTO.getyMargin()), pageToSign, null); } else { sap.setVisibleSignature( new Rectangle( signingDTO.getLocationX(), signingDTO.getLocationY(), signingDTO.getLocationX() + signingDTO.getSignWidth(), signingDTO.getLocationY() - signingDTO.getSignHeight()), pageToSign, null); } } stp.close(); NodeRef destinationNode = null; NodeRef originalDoc = null; boolean addAsNewVersion = false; if (signingDTO.getDestinationFolder() == null) { destinationNode = nodeRefToSign; nodeService.addAspect(destinationNode, ContentModel.ASPECT_VERSIONABLE, null); addAsNewVersion = true; } else { originalDoc = nodeRefToSign; destinationNode = createDestinationNode( file.getName(), signingDTO.getDestinationFolder(), nodeRefToSign); } if (destinationNode != null) { final ContentWriter writer = contentService.getWriter(destinationNode, ContentModel.PROP_CONTENT, true); if (writer != null) { writer.setEncoding(fileToSignContentReader.getEncoding()); writer.setMimetype("application/pdf"); writer.putContent(file); file.delete(); if (fileConverted != null) { fileConverted.delete(); } nodeService.addAspect( destinationNode, SigningModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); nodeService.setProperty( destinationNode, SigningModel.PROP_REASON, signingDTO.getSignReason()); nodeService.setProperty( destinationNode, SigningModel.PROP_LOCATION, signingDTO.getSignLocation()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNATUREDATE, new java.util.Date()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNEDBY, AuthenticationUtil.getRunAsUser()); if (newName != null) { nodeService.setProperty(destinationNode, ContentModel.PROP_NAME, newName); } final X509Certificate c = (X509Certificate) ks.getCertificate(alias); nodeService.setProperty( destinationNode, SigningModel.PROP_VALIDITY, c.getNotAfter()); nodeService.setProperty( destinationNode, SigningModel.PROP_ORIGINAL_DOC, originalDoc); if (!addAsNewVersion) { if (!nodeService.hasAspect(originalDoc, SigningModel.ASPECT_ORIGINAL_DOC)) { nodeService.addAspect( originalDoc, SigningModel.ASPECT_ORIGINAL_DOC, new HashMap<QName, Serializable>()); } nodeService.createAssociation( originalDoc, destinationNode, SigningModel.PROP_RELATED_DOC); } } } else { log.error("[" + fileNameToSign + "] Destination node is not a valid NodeRef."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Destination node is not a valid NodeRef."); } } else { log.error("[" + fileNameToSign + "] Unable to get PDF appearance signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get PDF appearance signature."); } } else { log.error("[" + fileNameToSign + "] Unable to create PDF signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to create PDF signature."); } } } } else { log.error("[" + fileNameToSign + "] Unable to get document to sign content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get document to sign content."); } if (pdfAFile != null) { pdfAFile.delete(); } return null; } else { log.error("[" + fileNameToSign + "] The document has no content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The document has no content."); } } catch (KeyStoreException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (ContentIOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (IOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (DocumentException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { log.error("[" + fileNameToSign + "] " + ex); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + ex.getMessage(), ex); } } } }
public PdfPTable createFirstTable() { // a table with three columns PdfPTable table = new PdfPTable(2); table.setSpacingBefore(50f); // Space before table table.setSpacingAfter(100f); // Space after table float[] columnWidths = {2f, 2f}; try { table.setWidths(columnWidths); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } PdfPCell cell; // we add a cell with colspan 3 cell = new PdfPCell(new Phrase("Patient Information")); cell.setColspan(2); cell.setBorder(Rectangle.BOTTOM); table.addCell(cell); cell = new PdfPCell(new Phrase("Name:")); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase(name)); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase("Patient ID:")); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase(Integer.toString(patient_ID))); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); // Blank row to add padding cell = new PdfPCell(new Phrase(" ")); cell.setColspan(2); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); //////////////////////////// cell = new PdfPCell(new Phrase("Date Issued:")); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase(dateIssued)); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase("Charge Date:")); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase(chargeDate)); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); // Blank row to add padding cell = new PdfPCell(new Phrase(" ")); cell.setColspan(2); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); ///////////////////// cell = new PdfPCell(new Phrase("Procedure")); cell.setColspan(2); cell.setBorder(Rectangle.BOTTOM); table.addCell(cell); cell = new PdfPCell(new Phrase(procedure)); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase(amount)); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); // Blank row to add padding cell = new PdfPCell(new Phrase(" ")); cell.setColspan(2); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); ///////////////////// cell = new PdfPCell(new Phrase("Total:")); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); cell = new PdfPCell(new Phrase(amount)); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); /* cell = new PdfPCell(new Phrase("1234 West Forest Drive, Fayetteville Arkansas")); cell.setColspan(4); table.addCell(cell); // now we add a cell with rowspan 2 cell = new PdfPCell(new Phrase("Cell with rowspan 3")); cell.setRowspan(3); table.addCell(cell); // we add the four remaining cells with addCell() table.addCell("row 1; cell 1"); table.addCell("row 1; cell 2"); table.addCell("row 1; cell 3"); table.addCell("row 1; cell 4"); table.addCell("row 2; cell 1"); //table.addCell("row 2; cell 2"); //table.addCell("row 3; cell 1"); * * */ return table; }
@Override public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); Image imghead = null; PdfContentByte cbhead = null; try { imghead = Image.getInstance("LogoSapito5.png"); imghead.setAbsolutePosition(0, 0); imghead.setAlignment(Image.ALIGN_CENTER); imghead.scalePercent(10f); cbhead = writer.getDirectContent(); PdfTemplate tp = cbhead.createTemplate(100, 150); tp.addImage(imghead); cbhead.addTemplate(tp, 100, 715); } catch (BadElementException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException ex) { Logger.getLogger(Cuentaspagar.class.getName()).log(Level.SEVERE, null, ex); } Phrase headPhraseImg = new Phrase(cbhead + "", FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL)); Calendar c1 = Calendar.getInstance(); Calendar c2 = new GregorianCalendar(); String dia, mes, annio; dia = Integer.toString(c1.get(Calendar.DATE)); mes = Integer.toString(c1.get(Calendar.MONTH)); annio = Integer.toString(c1.get(Calendar.YEAR)); java.util.Date fecha = new Date(); String fechis = dia + "/" + mes + "/" + annio; Paragraph parrafo5 = new Paragraph( fechis, FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLACK)); ColumnText.showTextAligned( writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo5), rect.getRight(450), rect.getTop(-80), 0); Paragraph parrafo7 = new Paragraph( "Empresa Sapito S.A. de C.V.", FontFactory.getFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD, BaseColor.BLACK)); ColumnText.showTextAligned( writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo7), rect.getBottom(250), rect.getTop(-60), 0); Paragraph parrafo8 = new Paragraph( "Cuentas por cobrar", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD, BaseColor.BLACK)); ColumnText.showTextAligned( writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo8), rect.getBottom(250), rect.getTop(-40), 0); ColumnText.showTextAligned( writer.getDirectContent(), Element.ALIGN_BOTTOM, new Phrase( " _________________________________________________________________________________ "), rect.getBorder(), rect.getTop(-24), 0); ColumnText.showTextAligned( writer.getDirectContent(), Element.ALIGN_BOTTOM, new Phrase( " _________________________________________________________________________________ "), rect.getBorder(), rect.getTop(-20), 0); Paragraph parrafo6 = new Paragraph( String.format("Pág %d", writer.getPageNumber()), FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLACK)); ColumnText.showTextAligned( writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(parrafo6), rect.getRight(-35), rect.getTop(-80), 0); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Logger logger = GenericUtilities.checkLoggedIn(request, response, false); String todo = request.getParameter("todo"); if (todo != null && todo.equals("printPDF")) { // --- stampa PDF --- Document doc = new Document(); File file = new File("filePDF_" + logger.getUser().getId() + ".pdf"); FileOutputStream os = new FileOutputStream(file); String str = file.getAbsolutePath(); Boolean printTeams = request.getParameter("hire") != null; Boolean printMatches = request.getParameter("match") != null; Boolean printChampResults = request.getParameter("champ") != null; try { // campionati a cui l'utente partecipa List<ChampionshipEntity> cl = MySQLConnection.getChampionshipOfUser(logger.getUser().getId()); // apri il documento PDF PdfWriter.getInstance(doc, os); doc.open(); doc.add( new Phrase( new Chunk( "Fantaservlet: utente " + logger.getUser().getName(), FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD)))); // per ogni campionato for (Iterator<ChampionshipEntity> it = cl.iterator(); it.hasNext(); ) { ChampionshipEntity champ = it.next(); printChampTitle(champ, doc); // --- stampa le rose di calciatori --- if (printTeams) { // prendi la lista delle squadre List<TeamEntity> teams = MySQLConnection.getTeamsOfChampionship(champ.getId()); for (Iterator<TeamEntity> it2 = teams.iterator(); it2.hasNext(); ) { TeamEntity team = it2.next(); printHiring( GenericUtilities.getPlayersListByRule( MySQLConnection.getHiring(team.getId()), 'D'), GenericUtilities.getPlayersListByRule( MySQLConnection.getHiring(team.getId()), 'C'), GenericUtilities.getPlayersListByRule( MySQLConnection.getHiring(team.getId()), 'A'), GenericUtilities.getPlayersListByRule( MySQLConnection.getHiring(team.getId()), 'P'), team, doc); } } if (printMatches || printChampResults) { // prendi la lista degli scontri List<Match> lm = GenericUtilities.getListOfMatches(champ.getId()); if (lm.size() > 0) { // --- stampa le partite del campionato --- if (printMatches) { printMatches(lm, GenericUtilities.getNumOfTeams(lm), doc); } // --- stampa la classifica --- if (printChampResults) { printRanking(GenericUtilities.getRanking(lm), GenericUtilities.isConcluse(lm), doc); } } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException sqle) { // TODO errore SQL } finally { // chiudi documento PDF doc.close(); } // stampa il pdf doDownload(request, response, str, "filepdf"); } else { // --- stamp pagina e form --- response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(Style.pageHeader(TITLE)); out.println("<form action=\"PrintPDF\" method=\"POST\">"); out.println("<input type=\"checkbox\"/ name=\"hire\" checked>Dati squadre<br/>"); out.println("<input type=\"checkbox\" name=\"match\"/ checked>Risultati partite<br/>"); out.println( "<input type=\"checkbox\" name=\"champ\"/ checked>Classifiche dei campionati<br/><br/>"); out.println(Style.hidden("todo", "printPDF")); out.println("<input type=\"submit\"/>"); out.println("</form>"); out.println(Style.pageFooter()); } }
public static void main(String[] args) throws MalformedURLException, IOException { // special font sizes Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0)); Font bf12 = new Font(FontFamily.TIMES_ROMAN, 12); Document document = new Document(); Font GRAY_NORMAL = new Font(FontFamily.HELVETICA, 18, Font.BOLD, BaseColor.GRAY); float fntSize = 6.7f; try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("invoice.pdf")); document.open(); // Add Image Image image1 = Image.getInstance( "E:/TECHVISIO/workspace/eServe/localRepo/src/main/webapp/static/images/Honda.jpg"); // Fixed Positioning image1.setAbsolutePosition(35f, 780f); // Scale to new height and new width of image image1.scaleAbsolute(50, 50); // Add to document document.add(image1); PdfPTable table = new PdfPTable(1); PdfPCell cell1 = new PdfPCell(new Paragraph("INVOICE", GRAY_NORMAL)); cell1.setBorder(Rectangle.NO_BORDER); cell1.setHorizontalAlignment(Element.ALIGN_RIGHT); cell1.setVerticalAlignment(Element.ALIGN_RIGHT); table.addCell(cell1); document.add(table); Paragraph clientName = new Paragraph( "Techvisio Solutions Pvt. Ltd.", FontFactory.getFont(FontFactory.COURIER, fntSize)); clientName.setAlignment(Element.ALIGN_LEFT); document.add(clientName); Paragraph address = new Paragraph("5/1608 Vasundhra", FontFactory.getFont(FontFactory.COURIER, fntSize)); address.setAlignment(Element.ALIGN_LEFT); document.add(address); Paragraph city = new Paragraph("Ghaziabad, 201012", FontFactory.getFont(FontFactory.COURIER, fntSize)); city.setAlignment(Element.ALIGN_LEFT); document.add(city); Paragraph state = new Paragraph("Uttar Pradesh", FontFactory.getFont(FontFactory.COURIER, fntSize)); state.setAlignment(Element.ALIGN_LEFT); document.add(state); // specify column widths float[] columnWidths = {2f, 8f, 3f}; // create PDF table with the given widths PdfPTable unitTable = new PdfPTable(columnWidths); // set table width a percentage of the page width unitTable.setWidthPercentage(100f); // insert column headings insertCell(unitTable, " ", Element.ALIGN_LEFT, 4, bfBold12, Rectangle.NO_BORDER); insertCell(unitTable, "S. No.", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX); insertCell(unitTable, "Product Description", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX); insertCell(unitTable, "Price", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX); insertCell(unitTable, " ", Element.ALIGN_LEFT, 4, bfBold12, Rectangle.BOX); insertCell(unitTable, "", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX); insertCell( unitTable, "unitId 2 Machine Serial No : HKID812K", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX); insertCell(unitTable, "80000", Element.ALIGN_LEFT, 1, bf12, Rectangle.BOX); document.add(unitTable); document.close(); writer.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } }