3

This is the code I have

<% 
Class.forName("com.mysql.jdbc.Driver");
class HeaderAndFooter extends PdfPageEventHelper {
   private String name = "";
   protected Phrase footer;
   protected Phrase header;
   PdfTemplate total;
   Font headerFont = new Font(FontFamily.COURIER, 13, Font.UNDERLINE);
   Font footerFont = new Font(FontFamily.HELVETICA, 11, Font.BOLD);
   Font footerFont1 = new Font(FontFamily.TIMES_ROMAN, 9,Font.BOLDITALIC);
   String date1;
   public HeaderAndFooter(String name) {
    super();
    this.name = name;
    header = new Phrase("***** Header *****");
    footer = new Phrase("**** Footer ****");
  }


  @Override
   public void onEndPage(PdfWriter writer, Document document) {
     PdfContentByte cb = writer.getDirectContent();
     String headerContent =name;
     String footerContent = headerContent;
     String log="C:/Users/Desktop/671.png";
     float gap = (document.getPageSize().getWidth())/ 30;
     float hei=(document.getPageSize().getHeight() - 60);
     Image img1=null;
     try{
         String message="";
         Connection con=null;
         Statement st;

         try{
                 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/87a", "root", "root");
                 st=con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
         String sqlText = "SELECT image FROM image"; 
         ResultSet rset = st.executeQuery(sqlText); 
         while(rset.next()) {
                 Blob image = rset.getBlob("image"); 
                 img1= Image.getInstance(image.getBytes(1, (int) image.length()));
         }
         }catch (SQLException ex) 
         {
                 message = "ERROR: " + ex.getMessage();
                 ex.printStackTrace();
                 } 
                 finally {
                 if (con != null) {
                     //closes the database connection
                     try {
                         con.close();
                     } catch (SQLException ex) {
                         ex.printStackTrace();
                     }
                 }
                 }
       Image img = Image.getInstance(img1); 
       //img.scalePercent((document.right()-document.left())/((float)img.getWidth())*100);
        cb.addImage(img, 570, 0, 0, 60, gap, hei);
     }catch(IOException e){}
     catch(DocumentException e){}
     ColumnText.showTextAligned(cb, Element.ALIGN_MIDDLE, new Phrase(String.format(" Page %d of", writer.getPageNumber()),footerFont), document.right() - 60 , document.bottom() - 15, 0);
  }
  }

OutputStream output=response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=details.pdf");
try{
        Document document = new Document(PageSize.A4, 20, 20, 70, 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();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gla", "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"));
 }
 document.add(new Paragraph(ds,new com.itextpdf.text.Font(bf, 12,Font.UNDERLINE)));
for(int i=0;i<4;i++){
  String str =(String) arrlist.get(i);
  document.add(new Paragraph(str,new com.itextpdf.text.Font(bf, 12)));
}
document.close();
}catch(IOException e){e.printStackTrace();} 
writer.flush();
writer.close();
output.close();
%>

Everything works, except that I dont get the total pages.

What am I missing?

Enno Shioji
  • 26,542
  • 13
  • 70
  • 109
Santino 'Sonny' Corleone
  • 1,735
  • 5
  • 25
  • 52
  • You might want to look at the [iText in Action, Second Edition](http://itextpdf.com/book/) sample [MovieCountries1](http://itextpdf.com/examples/iia.php?id=104) for a single pass solution and the sample [TwoPasses](http://itextpdf.com/examples/iia.php?id=118) for a double pass one. – mkl Jan 16 '14 at 13:16

1 Answers1

2

It looks like you're trying to set the total page number while in your onEndPage event. I don't believe it will work there (it might work but be one page number off). I think you'll have to wait until the pdf is complete and then stamp it with the total page numbers. Here's how I do it in vb.net (w/ itextsharp); I bet you can extract what you need out of it:

    ''' <summary>
    ''' Adds the page numbers to the bottom right hand side of the page
    ''' </summary>
    ''' <param name="PdfFile">The pdf file that needs numbering</param>
    ''' <returns>A byte array containing the numbered pdf file</returns>
    ''' <remarks>This is a stamping operation</remarks>
    Protected Shared Function AddPageNumbers(PdfFile As Byte()) As Byte()

        'prepare font
        Dim _bfTimes As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)

        Dim mem As New LengthFixingStream()

        Dim _reader As New PdfReader(PdfFile)
        Dim _stamper As New PdfStamper(_reader, mem)


        Dim PageCount As Integer = _reader.NumberOfPages
        For i As Integer = 1 To PageCount
            Dim _content As PdfContentByte = _stamper.GetOverContent(i)
            _content.SaveState()
            _content.BeginText()
            _content.SetFontAndSize(_bfTimes, 8)
            _content.SetTextMatrix(531, 18)
            _content.ShowText(String.Format("Page {0} of {1}", i, PageCount))
            _content.EndText()
            _content.RestoreState()

        Next

        _stamper.Close()

        AddPageNumbers = mem.GetBuffer()

    End Function

If you can't work it out from that, post back.

This SO post addresses your other issue: Resize image

Community
  • 1
  • 1
agileMike
  • 453
  • 3
  • 14
  • Thnx for the reply.I got the resize part.Regarding the pagenumber,I know we need to read the pdffile and stamp it but I dont know how to pass the file to the pdfreader as bytestream. – Santino 'Sonny' Corleone Jan 14 '14 at 04:23
  • Check out this SO question: [How to convert iTextPDF Document to Byte Array](http://stackoverflow.com/questions/11897290/how-to-convert-itextpdf-document-to-byte-array); it looks the code in the OP does what you want. Instead of using OutputStream, it makes use of ByteArrayOutputStream, which has a toByteArray method. – agileMike Jan 15 '14 at 13:54
  • I think you're nearly there and the comment by @mkl pointed out a really nice example. Combining the info there with my code above you end up with something like this: – agileMike Jan 19 '14 at 16:57
  • Oops, I hit [Enter] too soon. Anyway, use a ByteArrayOutputStream and after you close the document, create a reader and a stamper and iterate through it to stamp your page numbers. I'm a .net programmer so I don't have a jsp dev environment set up, but I'd be happy to take a stab at the code with the understanding that I can't test it. Just post back if you'd like me to post a new answer with that code. – agileMike Jan 19 '14 at 17:04
  • I tried converting to bytearray but it somehow gets stuck and nothing appears on the screen.On the console I get this error getoutputstream has already been called – Santino 'Sonny' Corleone Jan 22 '14 at 10:08
  • You'll probably have to instantiate another bytearrayoutputstream for the stamper and put that in the response instead of the original one. – agileMike Jan 22 '14 at 23:47
  • You do `response.getOutputStream()` before you do `response.setHeader`. Try to set all headers before getting the output stream. – mkl Jan 23 '14 at 06:08