
« 返回到 Development
Generate PDF File in Portlet
Community: developing-on-liferay
Table of Contents [-]
Introduction #
Liferay has a "Reports" portlet, which is a full-fledged report application. It's cool!
Sometimes a client may ask for a PDF file for simple reporting purposes. This can be a small portlet using a ResourceURL. The ResourceURL is as specified in JSR-286.
This method uses iText for generating PDF's. The AGPL that governs iText does not allow its use for closed-source projects. Use Liferay's OpenOffice/LibreOffice integration for these type projects.
Environment #
- Liferay 5.1.2
- Tomcat 6.0
- MySQL
JSP Side #
<input type="button" value="Submit" onClick="location.href = '<portlet:resourceURL><portlet:param name="reportType" value="pdf" /></portlet:resourceURL>'" />
Portlet Java Code #
public void serveResource(ResourceRequest req, ResourceResponse res) throws PortletException, IOException { String rType = ParamUtil.getString(req, "reportType"); HttpServletRequest request = PortalUtil.getHttpServletRequest(req); HttpSession session = request.getSession(); ThemeDisplay themeDisplay = (ThemeDisplay)req.getAttribute(WebKeys.THEME_DISPLAY); Company company = themeDisplay.getCompany(); if(rType != null && rType.equals("pdf")) { try { String msg = "Latest Weather Report"; Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); document.add(new Paragraph(msg)); document.add(Chunk.NEWLINE); document.add(new Paragraph("It is a sunny day today.")); document.close(); res.setContentType("application/pdf"); res.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate"); res.setContentLength(baos.size()); OutputStream out = res.getPortletOutputStream(); baos.writeTo(out); out.flush(); out.close(); } catch (Exception e2) { e2.System.out.println("Error in " + getClass().getName() + "\n" + e2); } } else { try { Workbook wb = new HSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("new sheet"); Row row = sheet.createRow((short)0); Cell cell = row.createCell(0); cell.setCellValue(1); row.createCell(1).setCellValue(1.2); row.createCell(2).setCellValue( createHelper.createRichTextString("This is a string")); row.createCell(3).setCellValue(true); res.setContentType("application/vnd.ms-excel"); res.addProperty( HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate"); OutputStream out = res.getPortletOutputStream(); wb.write(out); out.flush(); out.close(); } catch (Exception e) { System.out.println("Exception occurred ..."); } } }
Future Enhancement #
(1) Generate an Excel report
87450 查看