使用Servlet生成PDF文件并在新浏览器选项卡中显示PDF文件 - PDF文件为空。

3

我有一个现有的servlet,可以提供给我一个pdf字节数组:

byte[] pdf = myService.getPdf(myArgs);
response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, postcheck=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentLength(pdf.length); 
ServletOutputStream out = response.getOutputStream();
out.write(pdf);
out.flush();
out.close();

// for test: byte[] pdf
File testfile = new File("C:\\mytestpath\\mytest.pdf");
FileOutputStream fos = new FileOutputStream(testfile);
fos.write(pdf);
fos.flush();
fos.close();

我在servlet中写了一个测试pdf文件来检查myService.getPdf()的返回值。测试文件没问题,我可以在Acrobat Reader中打开这个有效的文件。

现在是我的JQuery-JavaScript代码:

function generatePDF(url) {
    currentRequest = $.ajax({
    url: url,
    type: "GET",
    success: function(data) {
        var blob = new Blob([data], {type: 'application/pdf'});
        var fileURL = window.URL.createObjectURL(blob);
        window.open(fileURL, "_blank");               
        },
    error: function() {         
        console.error("test in generatePDF error");
        // use here other jquery mobile functions
        }
    }); 
}

我想在我的servlet中生成一个PDF字节数组,并在新的浏览器选项卡中显示PDF。通过我的实现,会打开一个新的浏览器选项卡(地址行:blob:http%3A // localhost%3A8080 / 3fd5808b-758b-4076-94c9-af9884f631a3)。但是PDF文件为空,PDF文件的页面大小正确。我该如何解决这个问题?我需要在新的浏览器选项卡中获得名为myid.pdf的有效PDF。谢谢您的提示,Thomas。
2个回答

1
你可以在新窗口中打开servlet的URL。不需要进行AJAX调用或JQuery。
在servlet中,你可以添加头信息,提示浏览器如果用户选择保存文件应建议的文件名。
response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);

我完全同意,没有必要使用ajax或jquery请求。你只需要设置头文件来建议浏览器如何处理文件... +1 - MaVRoSCy
是的,我选择了一种没有使用 AJAX 的解决方案。 - Thomas Rademacher

0
public class PdfSheetGen extends HttpServlet {
    private static final long serialVersionUID = 1L;



    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         response.setContentType("appliction/pdf");
         Document document=new Document();
         Connection con=null;
          PreparedStatement ps=null;
          String sql=null;
          ResultSet rs=null;

          try{
              PdfWriter.getInstance(document, new FileOutputStream("D:/Details.pdf"));
              document.addAuthor("Management");
              document.addCreationDate();
              document.addProducer();
              document.addCreator("tech");
              document.addTitle("Inventory");
              document.setPageSize(PageSize.LETTER);
              document.open();
              Image image=Image.getInstance("D:\\branch.png");
              image.scaleAbsolute(120f, 120f);
              document.add(image);

              PdfPTable table=new PdfPTable(5);
              PdfPCell cell = new PdfPCell (new Paragraph ("Details"));

              cell.setColspan (5);
              cell.setHorizontalAlignment (Element.ALIGN_CENTER);
              cell.setPadding (10.0f);
              cell.setBackgroundColor (new BaseColor (140, 221, 8));
              table.addCell(cell);
              table.addCell("ID");
              table.addCell("Branch_Name");
              table.addCell("Address");
              table.addCell("Contact_p");
              table.addCell("Email");

              con=DbConnection.getCon();
              sql="select * from branch";
              ps=con.prepareStatement(sql);
              rs=ps.executeQuery();

              while (rs.next()) {
                  table.addCell(rs.getString("id"));
                table.addCell(rs.getString("Branch_name"));
                table.addCell(rs.getString("address"));
                table.addCell(rs.getString("contactp"));
                table.addCell(rs.getString("email"));

            }
              document.add(table);
              document.add(new Paragraph("Branch Details Generated On - "+new Date().toString()));
              document.close();

          }catch(Exception e){
              e.printStackTrace();
          }
          finally{
              try{
                  if(con!=null){
                      con.close();
                  }
                  if(ps!=null){
                      ps.close();
                  }
                  if(rs!=null){
                      rs.close();
                  }
              }catch(Exception e){
                  e.printStackTrace();
              }
          }


    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接