2

I have this code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try{
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=details.pdf");
        try{
        Document document = new Document(PageSize.A4, 20, 20, 130, 20);
        PdfWriter writer=PdfWriter.getInstance(document, output);
        document.open();
        BaseFont bf = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        writer.setPageEvent(new HeaderAndFooter(date));
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        List arrlist = new ArrayList();
        List arrlist1 = new ArrayList();//user list
        List arrlist2 = new ArrayList();//time list
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/765a", "root", "root");
        Statement st=con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
        ResultSet rs=st.executeQuery("SELECT * FROM user_start2 where date='"+date+"' ");
         while(rs.next()){
         arrlist.add(rs.getString("data"));
         arrlist1.add(rs.getString("users"));
         arrlist2.add(rs.getString("strtime"));
         }
         for(int i=0;i<interval+1;i++){
          String str =(String) arrlist.get(i);
          String str1 ='\n'+(String) arrlist1.get(i);
          String str2 =(String) arrlist2.get(i);
          String string =str.replace("<p>","\n").replace("</p>", "\n");
          document.add(new Paragraph(str1+"("+str2+")",new com.itextpdf.text.Font(bf, 10)));
          document.add(new Paragraph(str2,new com.itextpdf.text.Font(bf, 10)));
          document.add(new Paragraph(string,new com.itextpdf.text.Font(bf, 12)));
        }
        document.close();
        response.setContentLength(output.size());
         OutputStream os = response.getOutputStream();
         output.writeTo(os);
         os.flush();
         os.close();
        con.close();
        }catch(IOException e){e.printStackTrace();}
            }catch(IOException e){e.printStackTrace();} 
        catch(DocumentException e) {}
        catch(Exception e) {    
    }
        //PDF READER
          // Create a reader  
        try{
        OutputStream out = new ByteArrayOutputStream(); 
        PdfReader reader = new PdfReader(output.toByteArray());
        PdfStamper stamper = new PdfStamper(reader, out);
        Document document = new Document(); 
        document.open();
        int n = reader.getNumberOfPages();
        PdfContentByte cbq;
        Font headerFont = new Font(FontFamily.COURIER, 13, Font.UNDERLINE);
        for (int i = 1; i <= n; i++) {
            cbq = stamper.getOverContent(i);
             ColumnText ct = new ColumnText( cbq );
             ct.setSimpleColumn( 300 , 300, 50, 50 , 150, Element.ALIGN_CENTER );
              ct.addElement( new Paragraph( "Mathias" , headerFont ) );
              ct.go();
        }
        // Close the stamper
            stamper.close();
            reader.close();
            document.close();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

I am trying to add page numbers to my pdf but this above code doesnt work.Right now as an example I am just adding text "mathias" to check if it works but the text "mathias" doesnt appear on the pdf page.Everything else works fine,the headers,text on the pdf get displayed but not the data from the stamper.

I also tried using this

 for (int i = 1; i <= n; i++) {
            getHeaderTable(i, n).writeSelectedRows(0, -1, 34, 803, stamper.getOverContent(i));
        }

public static PdfPTable getHeaderTable(int x, int y) {
            PdfPTable table = new PdfPTable(2);
            table.setTotalWidth(527);
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(20);
            table.getDefaultCell().setBorder(Rectangle.BOTTOM);
            table.addCell("FOOBAR FILMFESTIVAL");
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(String.format("Page %d of %d", x, y));
            return table;
        }

But nothing appears from the stamper.

Am I missing something?

Santino 'Sonny' Corleone
  • 1,735
  • 5
  • 25
  • 52
  • Your stamper writes to `out` but you don't use out later on. Thus, your stamped changes get lost. – mkl Jan 27 '14 at 06:20
  • So what should i add? – Santino 'Sonny' Corleone Jan 27 '14 at 06:22
  • You mean I need to close it?Also do I need to create a new document while reading? – Santino 'Sonny' Corleone Jan 27 '14 at 06:34
  • First of all, where do you expect the PDF with the stamped additions to go? You do not seem to want those additions to be present in the PDF returned via HTTP; after all you explicitly send the unstamped PDF as response before even starting to stamp. Furthermore, *You mean I need to close it* - No, you need to use it. Currently you put the stamped PDF in your `ByteArrayOutputStream out` but later on do nothing with that stream. Thus, as soon as `out` is out-of-scope, that new PDF is lost. So please first state what you want to achieve . – mkl Jan 27 '14 at 07:42
  • I want to add the the text(in this case)/pagenumber to my pdf.But I have no idea how to do it using pdfstamper... – Santino 'Sonny' Corleone Jan 27 '14 at 07:49
  • The stamping code looks ok. Simply don't throw away the result in your `ByteArrayOutputStream out`. – mkl Jan 27 '14 at 08:05
  • Please could you answer it for me below.I have been strugling with this for quiet sometime – Santino 'Sonny' Corleone Jan 27 '14 at 08:07
  • You have the result in your `ByteArrayOutputStream out`. You merely need to put that result somewhere. Thus please clarify, where do you want the PDF with the stamped additions to go? Shall it be saved in some file locally? – mkl Jan 27 '14 at 08:12
  • To the same pdf like the one with all the database data.Do I need to create a new pdf or something? – Santino 'Sonny' Corleone Jan 27 '14 at 09:19

1 Answers1

3

What mkl is trying to explains is very simple. You are sending a PDF document to the browser using:

response.setContentLength(output.size());
OutputStream os = response.getOutputStream();
output.writeTo(os);

However, this document is a PDF document before stamping, hence it shouldn't surprise you that you don't see any changes applied to the document with PdfStamper. Please remove these lines and take a look at this code:

//PDF READER
// Create a reader  
try{
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    PdfReader reader = new PdfReader(output.toByteArray());
    PdfStamper stamper = new PdfStamper(reader, out);
    int n = reader.getNumberOfPages();
    PdfContentByte cbq;
    Font headerFont = new Font(FontFamily.COURIER, 13, Font.UNDERLINE);
    for (int i = 1; i <= n; i++) {
        cbq = stamper.getOverContent(i);
        ColumnText ct = new ColumnText( cbq );
        ct.setSimpleColumn( 300 , 300, 50, 50 , 150, Element.ALIGN_CENTER );
        ct.addElement( new Paragraph( "Mathias" , headerFont ) );
        ct.go();
    }
    // Close the stamper
    stamper.close();
    reader.close();
    response.setContentLength(out.size());
    OutputStream os = response.getOutputStream();
    out.writeTo(os);
} catch (DocumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Note that I removed the Document document = new Document(); from this snippet. Please read the documentation. You don't need a Document instance when using PdfStamper.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • but using `OutputStream out` I get errors on out.size()(`The method size() is undefined for the type OutputStream`) and on out.writeTo(os) (`The method writeTo(OutputStream) is undefined for the type OutputStream`) – Santino 'Sonny' Corleone Jan 27 '14 at 09:46
  • Simply declare `ByteArrayOutputStream out` instead. You set it to a `ByteArrayOutputStream` after all... – mkl Jan 27 '14 at 10:27
  • I've updated my answer. Please don't use statements such as "it doesn't work", be more specific! http://lowagie.com/doesntwork – Bruno Lowagie Jan 27 '14 at 10:44
  • 2
    @user3040563 What *doesnt work*? Have you removed the wrong lines, including your original `response.setContentLength(output.size());` ... `output.writeTo(os);` ... `os.close();`? – mkl Jan 27 '14 at 11:01