public Element exec(Element metadata, ServiceContext context) throws Exception { Element htmlDoc = metadata.getChild("html"); XMLOutputter printer = new XMLOutputter(); String htmlContent = printer.outputString(htmlDoc); File tempDir = (File) context.getServlet().getServletContext().getAttribute("javax.servlet.context.tempdir"); File tempFile = File.createTempFile(TMP_PDF_FILE, ".pdf", tempDir); OutputStream os = new FileOutputStream(tempFile); try { ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(htmlContent); renderer.layout(); renderer.createPDF(os); } finally { os.close(); } Element res = BinaryFile.encode(200, tempFile.getAbsolutePath(), true); return res; }
@Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { arg2.doFilter(arg0, arg1); HttpServletRequest request = (HttpServletRequest) arg0; ResponseWrapper response = (ResponseWrapper) arg1; if ("doOperation".equals(request.getParameter("method")) && "PRINT_ALL_DOCUMENTS".equals(request.getParameter("operationType"))) { try { // clean the response html and make a DOM document out of it String responseHtml = clean(response.getContent()); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(responseHtml.getBytes())); // alter paths of link/img tags so itext can use them properly patchLinks(doc, request); // structure pdf document ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(doc, ""); renderer.layout(); // create the pdf ByteArrayOutputStream pdfStream = new ByteArrayOutputStream(); renderer.createPDF(pdfStream); // concatenate with other docs final Person person = (Person) request.getAttribute("person"); final StudentCandidacy candidacy = getCandidacy(request); ByteArrayOutputStream finalPdfStream = concatenateDocs(pdfStream.toByteArray(), person, candidacy); byte[] pdfByteArray = finalPdfStream.toByteArray(); // associate the summary file to the candidacy associateSummaryFile(pdfByteArray, person.getStudent().getNumber().toString(), candidacy); // redirect user to the candidacy summary page response.reset(); response.sendRedirect(buildRedirectURL(request, candidacy)); response.flushBuffer(); } catch (ParserConfigurationException e) { logger.error(e.getMessage(), e); } catch (SAXException e) { logger.error(e.getMessage(), e); } catch (DocumentException e) { logger.error(e.getMessage(), e); } } }
private void createPdfStream( final String content, final String baseUrl, final OutputStream outputStream) throws DocumentException, IOException, URISyntaxException { ITextRenderer renderer = new ITextRenderer(); // for unicode renderer.getFontResolver().addFont(FONT_FILE_PATH, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); renderer.setDocumentFromString(content, baseUrl); renderer.layout(); renderer.createPDF(outputStream); }
private File writePdf() throws IOException, DocumentException { ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString( String.format( XHTML_PAGE, beanItem.getSubject(), beanItem.getSubject(), beanItem.getContent())); renderer.layout(); File file = File.createTempFile(beanItem.getSubject(), "pdf"); file.deleteOnExit(); try (OutputStream os = new FileOutputStream(file)) { renderer.createPDF(os); } return file; }
/** Add PDF meta values to the target PDF document. */ private void addPdfMetaValuesToPdfDocument(ITextRenderer renderer) { Iterator pdfNameIter = this.pdfInfoValues.keySet().iterator(); while (pdfNameIter.hasNext()) { PdfName pdfName = (PdfName) pdfNameIter.next(); PdfString pdfString = (PdfString) pdfInfoValues.get(pdfName); XRLog.render(Level.FINEST, "pdfName=" + pdfName + ", pdfString=" + pdfString); renderer.getOutputDevice().getWriter().getInfo().put(pdfName, pdfString); } if (XRLog.isLoggingEnabled()) { XRLog.render( Level.FINEST, "added " + renderer.getOutputDevice().getWriter().getInfo().getKeys()); } }
public static void embedFonts(ITextRenderer renderer) { final PropertySet propertySet = Properties.instance().getPropertySet(); for (final String propertyName : propertySet.getPropertiesStartsWith("oxf.fr.pdf.font.path")) { final String path = StringUtils.trimToNull(propertySet.getString(propertyName)); if (path != null) { try { // Overriding the font family is optional final String family; { final String[] tokens = StringUtils.split(propertyName, '.'); if (tokens.length >= 6) { final String id = tokens[5]; family = StringUtils.trimToNull( propertySet.getString("oxf.fr.pdf.font.family" + '.' + id)); } else { family = null; } } // Add the font renderer .getFontResolver() .addFont(path, family, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, null); } catch (Exception e) { logger.warn( "Failed to load font by path: '" + path + "' specified with property '" + propertyName + "'"); } } } }
private boolean encode(ServletOutputStream servletOutputStream, String content) throws Exception { try { // parse the markup into an xml Document final Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new InputSource(new StringReader(content))); final ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(doc, null); renderer.layout(); renderer.createPDF(servletOutputStream); } finally { servletOutputStream.flush(); } return true; }
public static byte[] XHTML2PDF(String xhtml) throws IOException { byte[] pdf = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { ITextRenderer itextRenderer = new ITextRenderer(); itextRenderer.setDocumentFromString(xhtml); itextRenderer.layout(); itextRenderer.createPDF(byteArrayOutputStream); pdf = byteArrayOutputStream.toByteArray(); } catch (Exception e) { logger.error(e.getMessage(), e); logger.error("vvv--- Offending XHTML ---vvv"); logger.error(xhtml); throw new IOException(e.getMessage()); } return pdf; }
String convert2Pdf(String htmlFileName, String pdfFileName) { try { String url = new File(htmlFileName).toURI().toURL().toString(); // Debugging: System.out.println(""+url); OutputStream os = new FileOutputStream(pdfFileName); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(url); renderer.layout(); renderer.createPDF(os); os.close(); } catch (DocumentException e) { System.out.println("Error in the html to pdf converter"); } catch (IOException e) { System.out.println("Error in the html to pdf converter"); } catch (Exception e) { System.out.println("Error in the html to pdf converter"); } return pdfFileName; }
protected void readInput( final PipelineContext pipelineContext, final ProcessorInput input, Config config, OutputStream outputStream) { final ExternalContext externalContext = NetUtils.getExternalContext(); // Read the input as a DOM final Document domDocument = readInputAsDOM(pipelineContext, input); // Create renderer and add our own callback final float DEFAULT_DOTS_PER_POINT = 20f * 4f / 3f; final int DEFAULT_DOTS_PER_PIXEL = 14; final ITextRenderer renderer = new ITextRenderer(DEFAULT_DOTS_PER_POINT, DEFAULT_DOTS_PER_PIXEL); // Embed fonts if needed, based on configuration properties embedFonts(renderer); try { final ITextUserAgent callback = new ITextUserAgent(renderer.getOutputDevice()) { // Called for: // // - CSS URLs // - image URLs // - link clicked / form submission (not relevant for our usage) // - resolveAndOpenStream below public String resolveURI(String uri) { // Our own resolver // All resources we care about here are resource URLs. The PDF pipeline makes sure // that the servlet // URL rewriter processes the XHTML output to rewrite resource URLs to absolute paths, // including // the servlet context and version number if needed. In addition, CSS resources must // either use // relative paths when pointing to other CSS files or images, or go through the XForms // CSS rewriter, // which also generates absolute paths. // So all we need to do here is rewrite the resulting path to an absolute URL. // NOTE: We used to call rewriteResourceURL() here as the PDF pipeline did not do URL // rewriting. // However this caused issues, for example resources like background images referred // by CSS files // could be rewritten twice: once by the XForms resource rewriter, and a second time // here. return URLRewriterUtils.rewriteServiceURL( NetUtils.getExternalContext().getRequest(), uri, ExternalContext.Response.REWRITE_MODE_ABSOLUTE | ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_NO_CONTEXT); } // Called by: // // - getCSSResource // - getImageResource below // - getBinaryResource (not sure when called) // - getXMLResource (not sure when called) protected InputStream resolveAndOpenStream(String uri) { final String resolvedURI = resolveURI(uri); // TODO: Use xforms:submission code instead // Tell callee we are loading that we are a servlet environment, as in effect we act // like // a browser retrieving resources directly, not like a portlet. This is the case also // if we are // called by the proxy portlet or if we are directly within a portlet. final Map<String, String[]> headers = new HashMap<String, String[]>(); headers.put("Orbeon-Client", new String[] {"servlet"}); final ConnectionResult connectionResult = new Connection() .open( externalContext, new IndentedLogger(logger, ""), false, Connection.Method.GET.name(), URLFactory.createURL(resolvedURI), null, null, null, headers, Connection.getForwardHeaders()); if (connectionResult.statusCode != 200) { connectionResult.close(); throw new OXFException( "Got invalid return code while loading resource: " + uri + ", " + connectionResult.statusCode); } pipelineContext.addContextListener( new PipelineContext.ContextListener() { public void contextDestroyed(boolean success) { connectionResult.close(); } }); return connectionResult.getResponseInputStream(); } public ImageResource getImageResource(String uri) { final InputStream is = resolveAndOpenStream(uri); final String localURI = NetUtils.inputStreamToAnyURI(is, NetUtils.REQUEST_SCOPE); return super.getImageResource(localURI); } }; callback.setSharedContext(renderer.getSharedContext()); renderer.getSharedContext().setUserAgentCallback(callback); // renderer.getSharedContext().setDPI(150); // Set the document to process renderer.setDocument( domDocument, // No base URL if can't get request URL from context externalContext.getRequest() == null ? null : externalContext.getRequest().getRequestURL()); // Do the layout and create the resulting PDF renderer.layout(); final List pages = renderer.getRootBox().getLayer().getPages(); try { // Page count might be zero, and if so createPDF if (pages != null && pages.size() > 0) { renderer.createPDF(outputStream); } else { // TODO: log? } } catch (Exception e) { throw new OXFException(e); } finally { try { outputStream.close(); } catch (IOException e) { // NOP // TODO: log? } } } finally { // Free resources associated with the rendering context renderer.getSharedContext().reset(); } }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String templateClass = request.getParameter(AplosAppConstants.TEMPLATE_CLASS); if (templateClass == null || templateClass.equals("")) { return; } ServletContext servletContext = request.getSession().getServletContext(); AplosContextListener aplosContextListener = (AplosContextListener) servletContext.getAttribute(AplosScopedBindings.CONTEXT_LISTENER); String processedTemplateClass; if (PageBindingPhaseListener.getPrintTemplateOverrideMap().containsKey(templateClass)) { processedTemplateClass = PageBindingPhaseListener.getPrintTemplateOverrideMap().get(templateClass); } else { processedTemplateClass = templateClass; } PrintTemplate printTemplate = (PrintTemplate) Class.forName(processedTemplateClass).newInstance(); boolean createPdf = false; boolean createSizedPdf = false; if (request.getParameter(AplosAppConstants.CREATE_PDF) != null && request.getParameter(AplosAppConstants.CREATE_PDF).equals("true")) { createPdf = true; } if (request.getParameter(AplosAppConstants.CREATE_SIZED_PDF) != null && request.getParameter(AplosAppConstants.CREATE_SIZED_PDF).equals("true")) { createSizedPdf = true; } response.setHeader("Content-Disposition", "inline;"); StringInputStream input = null; BufferedOutputStream output = null; try { printTemplate.initialise(response, request); String templateOutput = printTemplate.getTemplateContent(); if (!createSizedPdf) { output = new BufferedOutputStream(response.getOutputStream()); if (createPdf) { ITextRenderer renderer = new ITextRenderer(); ApplicationUtil.getAplosContextListener().addFonts(renderer); renderer.setDocumentFromString(templateOutput); renderer.layout(); renderer.createPDF(output, true); response.setContentType("application/pdf"); } else { input = new StringInputStream(templateOutput); byte[] buffer = new byte[8192]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } } } catch (Exception e) { AplosContextListener.getAplosContextListener().handleError(e); input = new StringInputStream( "There was an error trying to create this report, please contact system support"); byte[] buffer = new byte[8192]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { } } if (input != null) { try { input.close(); } catch (IOException logOrIgnore) { } } } } catch (ClassNotFoundException cnfex) { AplosContextListener.getAplosContextListener().handleError(cnfex); } catch (IllegalAccessException iaex) { AplosContextListener.getAplosContextListener().handleError(iaex); } catch (InstantiationException iex) { AplosContextListener.getAplosContextListener().handleError(iex); } }