我的要求是使用来自数据库的一些数据创建一个动态报告pdf文件,我正在使用iText。 现在,我想在网页中显示这个pdf文件以及菜单,页眉,页脚等。
因此,如果用户有一些pdf查看器,则此pdf应显示在带有打印选项的用户计算机上以打印该pdf。
答案 0 :(得分:8)
这就是我这样做的方式。您可以在iframe或常规jsp中调用此操作
public class GeneratePdf extends ActionSupport{
private InputStream inputStream;
public String execute(){
HttpServletResponse response = ServletActionContext.getResponse();
Document document = new Document();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
PdfWriter.getInstance(document, buffer);
document.open();
// do your thing
document.close();
} catch (DocumentException e) {
e.printStackTrace();
}
byte[] bytes = null;
bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
if(bytes!=null){
inputStream = new ByteArrayInputStream ( bytes );
}
return SUCCESS;
}
public InputStream getInputStream() {
return inputStream;
}
}
在你的struts.xml
中 <action name="GeneratePdf" class="com.xxx.action.GeneratePdf">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">filename="test.pdf"</param>
<param name="bufferSize">1024</param>
</result>
</action>
答案 1 :(得分:0)
答案 2 :(得分:0)
public ByteArrayInputStream generatePDF(List<Object> items) {
try {
List<InputStream> listInputStream = new ArrayList<InputStream>();
for (int i = 0; i < items.size(); i++) {
listInputStream.add(new ByteArrayInputStream(getBytes(items.get(i)));
}
HttpServletResponse response = ServletActionContext.getResponse();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, buffer);
document.open();
PdfContentByte cb = writer.getDirectContent();
for (InputStream inputStream : listInputStream) {
PdfReader reader = new PdfReader(inputStream);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
document.setPageSize(reader.getPageSize(i));
document.newPage();
PdfImportedPage page = writer.getImportedPage(reader, i);
cb.addTemplate(page, 0, 0);
}
}
document.close();
byte[] bytes = null;
bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
return new ByteArrayInputStream(bytes);
} catch(Exception e){
System.out.println(e);
}
}