2

I'm currently trying to build a little webtool and tried to add a logo to a PDF using the preProcessor in DataExporter (Primefaces). I have set up a server where the logo is stored.

Now when I try to export the DataTable into a PDFI keep getting this error message:

com.lowagie.text.Document cannot be cast to com.itextpdf.text.Document

Thats the bean that contains the preProcessor method

    public void preProcessPDF (Object document)  throws IOException, BadElementException, DocumentException 
{
    Document pdf = (Document) document; 
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); 
    String logo = servletContext.getRealPath("") + File.separator + "http:" + File.separator + File.separator +"192.168.1.34:8080" + File.separator
    + "Bilder" + File.separator + "ubs.jpg";
    pdf.add(Image.getInstance(logo));

}

That is the xhtml file :

<h:commandButton value="Als PDF exportieren">

    <!--  <h:outputText value="Als PDF exportieren" />-->       
    <p:dataExporter type="pdf" target="modulbewertung"
        fileName="zusammenfassung_modulbewertung"
        preProcessor="#{handleEvents.preProcessPDF}"/>

</h:commandButton>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Akashi
  • 31
  • 4

1 Answers1

1

com.lowagie.text.Document cannot be cast to com.itextpdf.text.Document

This error message basically means that you're trying to cast an object of type com.lowagie.text.Document to an object of type com.itextpdf.text.Document, while the object isn't an instance of that at all. That's most likely happening in the below line:

Document pdf = (Document) document; 

You need to make sure that the import declaration for the Document is like below:

import com.lowagie.text.Document;

And thus not the other one. If you can't import it, then verify if you're using the right version of iText. Make sure that you don't have multiple different versioned iText libraries too.


Unrelated to the concrete problem, you should never ever use getRealPath(). Rather use getResource() or getResourceAsStream(). See also What does servletcontext.getRealPath("/") mean and when should I use it. Further, you don't need to fiddle around with File.separator to compose a URL.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • *You need to make sure that the import declaration for the Document is like below* ... or that the `document` object parameter is generated using a current iText version. The `com.lowagie` package indicates that an ancient iText version is in use, and unless the changed licensing is a problem, the new version shall indeed be used. – mkl Jul 15 '15 at 16:14
  • @mkl: PrimeFaces has indeed a problem with changed licensing and requires iText 2.1.x. – BalusC Jul 15 '15 at 19:58
  • In that case any installations including `com.itextpdf.**` classes are in license hell anyways... – mkl Jul 15 '15 at 20:43