Create PDF file with servlet and show PDF in new browser tab - PDF file is empty

I have an existing servlet that gives me a PDF byte array:

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();

      

I am writing a test pdf file in my servlet to check the return value of myService.getPdf (). The test file is fine, I can open this valid file in the acrobat reader.

And now my JQuery-JavaScript code:

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
        }
    }); 
}

      

I want to create a PDF byte array in my servlet and show the PDF in a new browser tab. My implementation has a new browsesr tab open (address bar: blob: http% 3A // localhost% 3A8080 / 3fd5808b-758b-4076-94c9-af9884f631a3). But the PDF file is empty, the page size of the PDF is ok. How can I solve this problem? I need a valid PDF named myid.pdf in a new browser tab.

Thanks for the advice, Thomas

+3


source to share


2 answers


You can just open the Servlet URL in a new window. No need for AJAX or JQuery call.

In your servlet, you can add headers that tell the browser what filename to suggest to the user if they want to save the file.



response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);

      

+1


source


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();
              }
          }


    }

      



0


source







All Articles