Fop generates pdf (xsl)

  When doing a project, you need to generate a PDF, and use the fop technology to achieve
  1. Download the corresponding jar package, not directly download the


  maven project 1.1 Maven project


 
2. Download the relevant fonts and template files


 
 2.1 Set the font path


 
 2.2 Set the template file data source


 

  3. Write Java code
   

public class FopReport extends BaseService{
	
	private static final String TYPE = ".pdf";

	private static final FopFactory fopFactory = FopFactory.newInstance();
	
	private static final String CONRIGURL = "fop.xml";
	
	
	/**
	 * Convert PDF files
	 * @param xsl template file
	 * @param policy data object
	 * @throws IOException
	 * @throws SAXException
	 */
	private ReportData createReport(File xsl,Object policy,boolean flag) throws IOException, SAXException {
		ReportData reportData = new ReportData();
		String userConfig = Configuration.getValue("pdf.font.path")+"/"+CONRIGURL;
		logger.info("Load font directory:"+Configuration.getValue("pdf.font.path")+"/"+CONRIGURL);
		fopFactory.setUserConfig(userConfig); //Read custom configuration
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, output);
			TransformerFactory factory = TransformerFactory.newInstance();
			String templateUrl = Configuration.getValue("pdf.template.path");
			File xslFile = new File(new File(templateUrl),xsl.toString());
			Transformer transformer = factory.newTransformer(new StreamSource(xslFile)); //template file
			logger.info("Load template:"+xslFile.toString());
			String str = "";
			if (!flag) {
				Ojbect2Xml ox = new Ojbect2Xml();
				str = ox.getFullXML(policy, "get");
			} else {
				str = policy.toString();
			}
			ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
					str.getBytes("UTF-8"));
			Charset charset = Charset.forName("UTF-8");
			Reader r = new InputStreamReader(bytearrayinputstream, charset);
			Source src = new StreamSource(r);
			Result res = new SAXResult(fop.getDefaultHandler());
			transformer.transform(src, res);
			reportData.setPdfData(output.toByteArray());
			writePdf(reportData);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			output.close();
		}
		return reportData;
	}
}

 
   4. Generate a byte stream file and write out the file stream, the final effect
   

   
   

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326762075&siteId=291194637