org.apache.fop.apps.MimeConstants Java Examples
The following examples show how to use
org.apache.fop.apps.MimeConstants.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApacheFopWorker.java From scipio-erp with Apache License 2.0 | 7 votes |
/** Returns a new Fop instance. Note: FOP documentation recommends using * a Fop instance for one transform run only. * @param out The target (result) OutputStream instance * @param outputFormat Optional output format, defaults to "application/pdf" * @param foUserAgent FOUserAgent object which may contains encryption-params in render options * @return Fop instance */ public static Fop createFopInstance(OutputStream out, String outputFormat, FOUserAgent foUserAgent) throws FOPException { if (UtilValidate.isEmpty(outputFormat)) { outputFormat = MimeConstants.MIME_PDF; } if (UtilValidate.isEmpty(foUserAgent)) { FopFactory fopFactory = getFactoryInstance(); foUserAgent = fopFactory.newFOUserAgent(); } Fop fop; if (out != null) { fop = fopFactory.newFop(outputFormat, foUserAgent, out); } else { fop = fopFactory.newFop(outputFormat, foUserAgent); } return fop; }
Example #2
Source File: PDFGenerationTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private void createAndValidate(String filename) throws Exception { SimpleReportFacade facade = SimpleReportFacade.newFacade(); File file = new File("src/test/resources/" + filename); XmlSimpleReport simpleReport = facade.unmarshall(file); try (FileOutputStream fos = new FileOutputStream("target/report.pdf")) { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, fos); Result result = new SAXResult(fop.getDefaultHandler()); facade.generatePdfReport(simpleReport, result); } File pdfReport = new File("target/report.pdf"); assertTrue(pdfReport.exists()); assertTrue(pdfReport.delete(), "Cannot delete PDF document (IO error)"); assertFalse(pdfReport.exists()); }
Example #3
Source File: PDFGenerationTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private void createAndValidate(String filename) throws Exception { DetailedReportFacade facade = DetailedReportFacade.newFacade(); File file = new File("src/test/resources/" + filename); XmlDetailedReport detailedReport = facade.unmarshall(file); try (FileOutputStream fos = new FileOutputStream("target/report.pdf")) { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, fos); Result result = new SAXResult(fop.getDefaultHandler()); facade.generatePdfReport(detailedReport, result); } File pdfReport = new File("target/report.pdf"); assertTrue(pdfReport.exists()); assertTrue(pdfReport.delete(), "Cannot delete PDF document (IO error)"); assertFalse(pdfReport.exists()); }
Example #4
Source File: PDFGenerationTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private void createAndValidate(String filename) throws Exception { SimpleCertificateReportFacade facade = SimpleCertificateReportFacade.newFacade(); File file = new File("src/test/resources/" + filename); XmlSimpleCertificateReport simpleReport = facade.unmarshall(file); try (FileOutputStream fos = new FileOutputStream("target/report.pdf")) { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, fos); Result result = new SAXResult(fop.getDefaultHandler()); facade.generatePdfReport(simpleReport, result); } File pdfReport = new File("target/report.pdf"); assertTrue(pdfReport.exists()); assertTrue(pdfReport.delete(), "Cannot delete PDF document (IO error)"); assertFalse(pdfReport.exists()); }
Example #5
Source File: DocuTest.java From Digital with GNU General Public License v3.0 | 6 votes |
private void startFOP(FopFactory fopFactory, File xslfo, File pdfOut) throws IOException, TransformerException, FOPException { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(pdfOut))) { // Step 3: Construct fop with desired output format Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out); // Step 4: Setup JAXP using identity transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // identity transformer // Step 5: Setup input and output for XSLT transformation // Setup input stream Source src = new StreamSource(xslfo); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Step 6: Start XSLT transformation and FOP processing transformer.transform(src, res); } }
Example #6
Source File: MCRFoFormatterFOP.java From mycore with GNU General Public License v3.0 | 6 votes |
@Override public void transform(MCRContent input, OutputStream out) throws TransformerException, IOException { try { final FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setProducer(new MessageFormat("MyCoRe {0} ({1})", Locale.ROOT) .format(new Object[] { MCRCoreVersion.getCompleteVersion(), userAgent.getProducer() })); final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out); final Source src = input.getSource(); final Result res = new SAXResult(fop.getDefaultHandler()); Transformer transformer = getTransformerFactory().newTransformer(); transformer.transform(src, res); } catch (FOPException e) { throw new TransformerException(e); } finally { out.close(); } }
Example #7
Source File: FORendererApacheFOP.java From docx4j-export-FO with Apache License 2.0 | 5 votes |
private String setupApacheFopMime(FOSettings settings) { String ret = settings.getApacheFopMime(); if (ret == null) { ret = MimeConstants.MIME_PDF; } return ret; }
Example #8
Source File: FOPAreaTreeHelper.java From docx4j-export-FO with Apache License 2.0 | 5 votes |
static org.w3c.dom.Document getAreaTreeViaFOP(WordprocessingMLPackage hfPkg, boolean useXSLT) throws Docx4JException, ParserConfigurationException, SAXException, IOException { // Currently FOP dependent! But an Antenna House version ought to be feasible. FOSettings foSettings = Docx4J.createFOSettings(); foSettings.setWmlPackage(hfPkg); foSettings.setApacheFopMime(MimeConstants.MIME_FOP_AREA_TREE); foSettings.setLayoutMasterSetCalculationInProgress(true); // avoid recursion // foSettings.getFeatures().add(ConversionFeatures.PP_PDF_APACHEFOP_DISABLE_PAGEBREAK_LIST_ITEM); // in 3.0.1, this is off by default // Since hfPkg is already a clone, we don't need PP_COMMON_DEEP_COPY // Plus it invokes setFontMapper, which does processEmbeddings again, and those fonts aren't much use to us here foSettings.getFeatures().remove(ConversionFeatures.PP_COMMON_DEEP_COPY); if (log.isDebugEnabled()) { foSettings.setFoDumpFile(new java.io.File(System.getProperty("user.dir") + "/hf.fo")); } ByteArrayOutputStream os = new ByteArrayOutputStream(); if (useXSLT) { Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL); } else { Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL); } InputStream is = new ByteArrayInputStream(os.toByteArray()); DocumentBuilder builder = XmlUtils.getNewDocumentBuilder(); return builder.parse(is); }
Example #9
Source File: FORendererApacheFOP.java From docx4j-export-FO with Apache License 2.0 | 4 votes |
protected Fop createFop(String userConfiguration, String outputFormat, OutputStream outputStream) throws FOPException { FopFactory fopFactory = getFopFactory(userConfiguration); return fopFactory.newFop(outputFormat != null ? outputFormat : MimeConstants.MIME_PDF, outputStream); }
Example #10
Source File: OutputServices.java From scipio-erp with Apache License 2.0 | 4 votes |
public static Map<String, Object> createFileFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) { Locale locale = (Locale) serviceContext.get("locale"); Delegator delegator = dctx.getDelegator(); String screenLocation = (String) serviceContext.remove("screenLocation"); Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext")); String contentType = (String) serviceContext.remove("contentType"); String filePath = (String) serviceContext.remove("filePath"); String fileName = (String) serviceContext.remove("fileName"); if (UtilValidate.isEmpty(screenContext)) { screenContext = new HashMap<>(); } screenContext.put("locale", locale); if (UtilValidate.isEmpty(contentType)) { contentType = "application/pdf"; } try { MapStack<String> screenContextTmp = RenderMapStack.createRenderContext(); // SCIPIO: Dedicated context class: MapStack.create(); screenContextTmp.put("locale", locale); Writer writer = new StringWriter(); // substitute the freemarker variables... ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()), EntityUtilProperties.getPropertyValue("widget", "screenfop.screenrenderer", dctx.getDelegator())); // SCIPIO: TODO: form widget renderer support //FormStringRenderer foFormRenderer = new MacroFormRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()), // EntityUtilProperties.getPropertyValue("widget", "screenfop.formrenderer", dctx.getDelegator()), request, response); ScreenRenderer screensAtt = ScreenRenderer.makeWithEnvAwareFetching(writer, screenContextTmp, foScreenStringRenderer); screensAtt.populateContextForService(dctx, screenContext); screenContextTmp.putAll(screenContext); // SCIPIO: TODO: form widget renderer support //screensAtt.getContext().put("formStringRenderer", foFormRenderer); WidgetRenderOptions.setInContext(screensAtt.getContext(), WidgetRenderOptions.create(dctx, locale).setWarnMissingFormRenderer(true)); // SCIPIO: for logging; see ModelScreenWidget screensAtt.render(screenLocation); // create the input stream for the generation StreamSource src = new StreamSource(new StringReader(writer.toString())); // create the output stream for the generation ByteArrayOutputStream baos = new ByteArrayOutputStream(); Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF); ApacheFopWorker.transform(src, null, fop); baos.flush(); baos.close(); fileName += UtilDateTime.nowAsString(); if ("application/pdf".equals(contentType)) { fileName += ".pdf"; } else if ("application/postscript".equals(contentType)) { fileName += ".ps"; } else if ("text/plain".equals(contentType)) { fileName += ".txt"; } if (UtilValidate.isEmpty(filePath)) { filePath = EntityUtilProperties.getPropertyValue("content", "content.output.path", "/output", delegator); } File file = new File(filePath, fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(baos.toByteArray()); fos.close(); } catch (Exception e) { // SCIPIO: 2018-10-09: Kept Exception for now Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); }
Example #11
Source File: FopTask.java From pcgen with GNU Lesser General Public License v2.1 | 4 votes |
/** * Run the FO to PDF/AWT conversion. This automatically closes any provided OutputStream for * this FopTask. */ @Override public void run() { try (OutputStream out = outputStream) { userAgent.setProducer("PC Gen Character Generator"); userAgent.setAuthor(System.getProperty("user.name")); userAgent.setCreationDate(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(0)))); userAgent.getEventBroadcaster().addEventListener(new FOPEventListener()); String mimeType; if (renderer != null) { userAgent.setKeywords("PCGEN FOP PREVIEW"); mimeType = MimeConstants.MIME_FOP_AWT_PREVIEW; } else { userAgent.setKeywords("PCGEN FOP PDF"); mimeType = org.apache.xmlgraphics.util.MimeConstants.MIME_PDF; } Fop fop; if (out != null) { fop = FOP_FACTORY.newFop(mimeType, userAgent, out); } else { fop = FOP_FACTORY.newFop(mimeType, userAgent); } Transformer transformer; if (xsltSource != null) { transformer = TRANS_FACTORY.newTransformer(xsltSource); } else { transformer = TRANS_FACTORY.newTransformer(); // identity transformer } transformer.setErrorListener(new FOPErrorListener()); transformer.transform(inputSource, new SAXResult(fop.getDefaultHandler())); } catch (TransformerException | FOPException | IOException e) { errorBuilder.append(e.getMessage()).append(Constants.LINE_SEPARATOR); Logging.errorPrint("Exception in FopTask:run", e); } catch (RuntimeException ex) { errorBuilder.append(ex.getMessage()).append(Constants.LINE_SEPARATOR); Logging.errorPrint("Unexpected exception in FopTask:run: ", ex); } }
Example #12
Source File: SiteInfoToolServlet.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Takes a DOM structure and renders a PDF * * @param doc * DOM structure * @param streamOut */ @SuppressWarnings("unchecked") protected void generatePDF(Document doc, OutputStream streamOut) { String xslFileName = "participants-all-attrs.xsl"; Locale currentLocale = rb.getLocale(); if (currentLocale!=null){ String fullLocale = currentLocale.toString(); xslFileName = "participants-all-attrs_" + fullLocale + ".xsl"; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName); if (inputStream == null){ xslFileName = "participants-all-attrs_" + currentLocale.getCountry() + ".xsl"; inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName); if (inputStream == null){ //We use the default file xslFileName = "participants-all-attrs.xsl"; } } IOUtils.closeQuietly(inputStream); } String configFileName = "userconfig.xml"; DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); InputStream configInputStream = null; try { configInputStream = getClass().getClassLoader().getResourceAsStream(configFileName); Configuration cfg = cfgBuilder.build(configInputStream); FopFactory fopFactory = FopFactory.newInstance(); fopFactory.setUserConfig(cfg); fopFactory.setStrictValidation(false); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); if (!StringUtils.isEmpty(ServerConfigurationService.getString("pdf.default.font"))) { // this allows font substitution to support i18n chars in PDFs - SAK-21909 FontQualifier fromQualifier = new FontQualifier(); fromQualifier.setFontFamily("DEFAULT_FONT"); FontQualifier toQualifier = new FontQualifier(); toQualifier.setFontFamily(ServerConfigurationService.getString("pdf.default.font", "Helvetica")); FontSubstitutions result = new FontSubstitutions(); result.add(new FontSubstitution(fromQualifier, toQualifier)); fopFactory.getFontManager().setFontSubstitutions(result); } Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, streamOut); InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName); Transformer transformer = transformerFactory.newTransformer(new StreamSource(in)); transformer.setParameter("titleName", rb.getString("sitegen.siteinfolist.title.name")); transformer.setParameter("titleId", rb.getString("sitegen.siteinfolist.title.id")); transformer.setParameter("titleSection", rb.getString("sitegen.siteinfolist.title.section")); transformer.setParameter("titleCredit", rb.getString("sitegen.siteinfolist.title.credit")); transformer.setParameter("titleRole", rb.getString("sitegen.siteinfolist.title.role")); transformer.setParameter("titleStatus", rb.getString("sitegen.siteinfolist.title.status")); Source src = new DOMSource(doc); transformer.transform(src, new SAXResult(fop.getDefaultHandler())); } catch (Exception e) { log.warn("{}.generatePDF(): {}", this, e.toString()); } finally { IOUtils.closeQuietly(configInputStream); } }
Example #13
Source File: FOP2PDFSerializer.java From sakai with Educational Community License v2.0 | 4 votes |
public FOP2PDFSerializer() { mimeType = MimeConstants.MIME_PDF; }
Example #14
Source File: FOP2RTFSerializer.java From sakai with Educational Community License v2.0 | 4 votes |
public FOP2RTFSerializer() { mimeType = MimeConstants.MIME_RTF; }
Example #15
Source File: FopTask.java From pcgen with GNU Lesser General Public License v2.1 | 4 votes |
/** * Run the FO to PDF/AWT conversion. This automatically closes any provided OutputStream for * this FopTask. */ @Override public void run() { try (OutputStream out = outputStream) { userAgent.setProducer("PC Gen Character Generator"); userAgent.setAuthor(System.getProperty("user.name")); userAgent.setCreationDate(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(0)))); userAgent.getEventBroadcaster().addEventListener(new FOPEventListener()); String mimeType; if (renderer != null) { userAgent.setKeywords("PCGEN FOP PREVIEW"); mimeType = MimeConstants.MIME_FOP_AWT_PREVIEW; } else { userAgent.setKeywords("PCGEN FOP PDF"); mimeType = org.apache.xmlgraphics.util.MimeConstants.MIME_PDF; } Fop fop; if (out != null) { fop = FOP_FACTORY.newFop(mimeType, userAgent, out); } else { fop = FOP_FACTORY.newFop(mimeType, userAgent); } Transformer transformer; if (xsltSource != null) { transformer = TRANS_FACTORY.newTransformer(xsltSource); } else { transformer = TRANS_FACTORY.newTransformer(); // identity transformer } transformer.setErrorListener(new FOPErrorListener()); transformer.transform(inputSource, new SAXResult(fop.getDefaultHandler())); } catch (TransformerException | FOPException | IOException e) { errorBuilder.append(e.getMessage()).append(Constants.LINE_SEPARATOR); Logging.errorPrint("Exception in FopTask:run", e); } catch (RuntimeException ex) { errorBuilder.append(ex.getMessage()).append(Constants.LINE_SEPARATOR); Logging.errorPrint("Unexpected exception in FopTask:run: ", ex); } }
Example #16
Source File: SiteInfoToolServlet.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Takes a DOM structure and renders a PDF * * @param doc * DOM structure * @param streamOut */ @SuppressWarnings("unchecked") protected void generatePDF(Document doc, OutputStream streamOut) { String xslFileName = "participants-all-attrs.xsl"; Locale currentLocale = rb.getLocale(); if (currentLocale!=null){ String fullLocale = currentLocale.toString(); xslFileName = "participants-all-attrs_" + fullLocale + ".xsl"; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName); if (inputStream == null){ xslFileName = "participants-all-attrs_" + currentLocale.getCountry() + ".xsl"; inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName); if (inputStream == null){ //We use the default file xslFileName = "participants-all-attrs.xsl"; } } IOUtils.closeQuietly(inputStream); } String configFileName = "userconfig.xml"; DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); InputStream configInputStream = null; try { configInputStream = getClass().getClassLoader().getResourceAsStream(configFileName); Configuration cfg = cfgBuilder.build(configInputStream); FopFactory fopFactory = FopFactory.newInstance(); fopFactory.setUserConfig(cfg); fopFactory.setStrictValidation(false); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); if (!StringUtils.isEmpty(ServerConfigurationService.getString("pdf.default.font"))) { // this allows font substitution to support i18n chars in PDFs - SAK-21909 FontQualifier fromQualifier = new FontQualifier(); fromQualifier.setFontFamily("DEFAULT_FONT"); FontQualifier toQualifier = new FontQualifier(); toQualifier.setFontFamily(ServerConfigurationService.getString("pdf.default.font", "Helvetica")); FontSubstitutions result = new FontSubstitutions(); result.add(new FontSubstitution(fromQualifier, toQualifier)); fopFactory.getFontManager().setFontSubstitutions(result); } Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, streamOut); InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName); Transformer transformer = transformerFactory.newTransformer(new StreamSource(in)); transformer.setParameter("titleName", rb.getString("sitegen.siteinfolist.title.name")); transformer.setParameter("titleId", rb.getString("sitegen.siteinfolist.title.id")); transformer.setParameter("titleSection", rb.getString("sitegen.siteinfolist.title.section")); transformer.setParameter("titleCredit", rb.getString("sitegen.siteinfolist.title.credit")); transformer.setParameter("titleRole", rb.getString("sitegen.siteinfolist.title.role")); transformer.setParameter("titleStatus", rb.getString("sitegen.siteinfolist.title.status")); Source src = new DOMSource(doc); transformer.transform(src, new SAXResult(fop.getDefaultHandler())); } catch (Exception e) { log.warn("{}.generatePDF(): {}", this, e.toString()); } finally { IOUtils.closeQuietly(configInputStream); } }
Example #17
Source File: FOP2PDFSerializer.java From sakai with Educational Community License v2.0 | 4 votes |
public FOP2PDFSerializer() { mimeType = MimeConstants.MIME_PDF; }
Example #18
Source File: FOP2RTFSerializer.java From sakai with Educational Community License v2.0 | 4 votes |
public FOP2RTFSerializer() { mimeType = MimeConstants.MIME_RTF; }
Example #19
Source File: PdfBookConverter.java From AsciidocFX with Apache License 2.0 | 4 votes |
@Override public void convert(boolean askPath, Consumer<String>... nextStep) { final Path currentTabPath = current.currentPath().get(); final Path currentTabPathDir = currentTabPath.getParent(); final Path configPath = asciiDocController.getConfigPath(); threadService.runActionLater(() -> { final Path pdfPath = directoryService.getSaveOutputPath(ExtensionFilters.PDF, askPath); docBookConverter.convert(false, docbook -> { indikatorService.startProgressBar(); logger.debug("PDF conversion started"); final Path docbookTempfile = IOHelper.createTempFile(currentTabPathDir, ".xml"); IOHelper.writeToFile(docbookTempfile, docbook, CREATE, WRITE, TRUNCATE_EXISTING); try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pdfPath.toFile()));) { // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(configPath.resolve("docbook-config/fo-pdf.xsl").toFile())); transformer.setParameter("highlight.xslthl.config", configPath.resolve("docbook-config/xslthl-config.xml").toUri().toASCIIString()); transformer.setParameter("admon.graphics.path", configPath.resolve("docbook/images/").toUri().toASCIIString()); transformer.setParameter("callout.graphics.path", configPath.resolve("docbook/images/callouts/").toUri().toASCIIString()); if (Objects.isNull(fopFactory)) { fopFactory = FopFactory.newInstance(configPath.resolve("docbook-config/fop.xconf.xml").toFile()); } Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputStream); // Setup input for XSLT transformation Source src = new StreamSource(docbookTempfile.toFile()); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Step 6: Start XSLT transformation and FOP processing transformer.transform(src, res); Files.deleteIfExists(docbookTempfile); // Result processing FormattingResults foResults = fop.getResults(); logger.info("Generated {} pages in total.", foResults.getPageCount()); } catch (Exception e) { logger.error("Problem occured while converting to PDF", e); } finally { indikatorService.stopProgressBar(); logger.debug("PDF conversion ended"); asciiDocController.addRemoveRecentList(pdfPath); } }); }); }