0

As a part of large webapp, I have a print function to print PDF files:

public void printResource(String path) {

    // load file
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(path);
    } catch (FileNotFoundException e) {
        LOGGER.error("Problem trying to load the file!",e);
    }

    // file settings
    DocFlavor docFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc document = new SimpleDoc(inputStream, docFormat, null);

    // get default print service
    PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
    PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();

    if (defaultPrintService != null) {
        DocPrintJob printJob = defaultPrintService.createPrintJob();

        try {
            printJob.print(document, attributeSet);
        } catch (PrintException e) {
            LOGGER.error("PrintException!",e);
        }

    } else {
        LOGGER.error("No printer has been found");
    }

    try {
        inputStream.close();
    } catch (IOException e) {
        LOGGER.error("Ignoring error closing inputStream");
    }
}

Sometimes, it works and sometimes it doesn't. When it doesn't work, the printed paper says:

PDF Error 10: PostScript Error: IOERROR

I'm trying to find a rule with the non-working PDF files, and one common think with them is that these PDF files has been edited by me (by the app) in other functionality of the webapp. The edition is made with the iText library

The code that I use to write to the PDF is the following one (The code has been modified to became simpler, so could have any sintax error):

public void signPDF(String path) {

    // PDF
    PdfReader reader = null;
    PdfStamper stamper = null;

    // stream
    OutputStream os = null;
    RandomAccessFile raf = null;

    try {

        // check for the first time
            reader = new PdfReader(path);
            raf = new RandomAccessFile(outPutPath, ACCESS_MODE_READ_AND_WRITE);
            os = Channels.newOutputStream(raf.getChannel());

            stamper = new PdfStamper(reader, os);
            stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSize(1));


        // prepare canvas to sign
        PdfContentByte canvas = stamper.getOverContent(reader.getNumberOfPages());


        // sign document
        String signature = "Signed";
        int verticalPosition = calculateVerticalPosition();

        Rectangle size = reader.getPageSize(reader.getNumberOfPages());
        ColumnText.showTextAligned(canvas, Element.ALIGN_BOTTOM, new Phrase(signature), size.getWidth() - (size.getWidth() - 100), size.getHeight() - verticalPosition, 0);

    } catch (DocumentException dEx) {
        LOGGER.error(ERROR_UNEXPECTED, dEx);
        throw new PDFException(Code.UNEXPECTED, ERROR_UNEXPECTED);
    } catch (IOException ioEx) {
        LOGGER.error(ERROR_IO, ioEx);
        throw new PDFException(Code.READ_WRITE, MessageFormat.format(ERROR_IO, path));
    } finally {

        // close stamper
        if (stamper != null) {
            try {
                stamper.close();
            } catch (DocumentException dEx) {
                LOGGER.error(ERROR_UNEXPECTED, dEx);
            } catch (IOException ioEx) {
                LOGGER.error(ERROR_IO, ioEx);
            }

        }

        // close reader
        if (reader != null) {
            reader.close();
        }

        // close os
        if (os != null) {
            try {
                os.close();
            } catch (IOException ioEx) {
                LOGGER.error(ERROR_IO, ioEx);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }

        // close raf
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException ioEx) {
                LOGGER.error(ERROR_IO, ioEx);
            } finally {
                IOUtils.closeQuietly(raf);
            }
        }

    }
Rafa Romero
  • 2,667
  • 5
  • 25
  • 51
  • 1
    Nobody can solve your problem if you don't share your PDFs. iText is a very powerful tool. You can use it to create top-notch PDFs that comply to ISO-32000, ISO-19005, etc... You can also use it to seriously break your PDFs. If you don't tell us how you broke your PDFs, we can't tell you how to fix them. – Bruno Lowagie Dec 23 '15 at 17:12
  • Hi @BrunoLowagie! I'm going to edit the question and add the code that edit the PDF! – Rafa Romero Dec 23 '15 at 17:14
  • @BrunoLowagie The non-edited PDFs are not being problematics, just the edited PDFs – Rafa Romero Dec 23 '15 at 17:20
  • 1
    `Element.ALIGN_BOTTOM` is the wrong value to define the horizontal alignment of the text added with `showTextAligned()`. This is also strange: `size.getWidth() - (size.getWidth() - 100)`. That's equal to `-100`. Why are you adding text at a position where nobody can see it? (Maybe that's causing the error: you're adding text outside the visible area of the page.) Also: it doesn't make sense to use a `RandomAccessFile` to create an `OutputStream`. Are you sure you aren't corrupting the file? Maybe there are other errors. Which version of iText are you using? – Bruno Lowagie Dec 23 '15 at 18:06
  • The added text is always visible. I have made lots of tests. Anyway, could be the "stamper.insertPage" corrupting the file? Is the "stamper.addSignature()" method better to write into the PDF than "ShowTextAligned"??? As soon as I can I will apply your corrections – Rafa Romero Dec 23 '15 at 18:24
  • Er... you haven't answered the question on the version you're using. `addSignature()` is a method to add a signature field. A signature field can be used to add a *real* digital signature. You're adding a *fake* signature (text or an image, not a digital signature that uses PKI). Show us a PDF so that we can see for ourselves if the PDF is corrupt. – Bruno Lowagie Dec 23 '15 at 18:33
  • I made a mistake too: `size.getWidth() - (size.getWidth() - 100)` equals `+100`. Why didn't you just write `100` instead of `size.getWidth() - (size.getWidth() - 100)`? Don't you know the saying: [Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live](http://stackoverflow.com/questions/876089/who-wrote-this-programing-saying-always-code-as-if-the-guy-who-ends-up-maintai)? You should clean up your code. – Bruno Lowagie Dec 23 '15 at 18:36
  • I can not tell you the version because I am not at the PC now, as soon as I can I will tell you. How can I show you a PDF? What about "stamper.insertPage()"? I am using it correctly? Thank you @Bruno! – Rafa Romero Dec 23 '15 at 18:56
  • I've never heard any complaints about `stamper.insertPage()`. I'm not sure if `reader.getNumberOfPages() + 1` is correct as a parameter, because I don't remember if the page count starts at 0 or at 1. However: if you have tested the PDFs and they show "No syntax errors" in Adobe Acrobat (e.g. when you run preflight), then there's a high chance that nothing is wrong with those files. – Bruno Lowagie Dec 23 '15 at 19:12
  • I have not tested the files with any software to test if they are corrupt. I will do and I tell you the result! Thank you! – Rafa Romero Dec 23 '15 at 19:15
  • I'm using 5.5.6 version! – Rafa Romero Dec 24 '15 at 08:17
  • That should work. Did you already have a chance to Preflight the PDFs? – Bruno Lowagie Dec 24 '15 at 08:46
  • I was on it, but I have not an Acrobat PDF PRO license. Any other way to check the integrity of the PDF file? – Rafa Romero Dec 24 '15 at 08:59
  • Share the PDF and I'm sure there are people on SO who'll check the PDF for you. – Bruno Lowagie Dec 24 '15 at 09:01
  • I've checked it online. The results is the following: http://jpst.it/E9Jq – Rafa Romero Dec 24 '15 at 09:06
  • I assume that you have a PDF/A document. In that case, your code is wrong. You should use `PdfAStamper` instead of `PdfStamper`. Or you should remove the PDF/A status from the PDF. – Bruno Lowagie Dec 24 '15 at 10:35
  • I'm not sure what kind of PDF I have because the documents will be added by users to the webapp. How can I remove the PDF/A status to have all PDF as non PDF/A? – Rafa Romero Dec 24 '15 at 10:39
  • I fear that your question is too complex to have it answered on SO. (1.) Removing the PDF/A status may not solve the printing problem. (2.) There's a 99% chance that iText isn't the culprit of the problem. (3.) There's a 66% chance that your code isn't the culprit of the problem. Please hire a specialist who can come on-premise to solve your problem. This is not something that can easily be fixed remotely. – Bruno Lowagie Dec 24 '15 at 10:56
  • I suposse that, anyway, thank you for your help! Congrats for iText, big tool! – Rafa Romero Dec 24 '15 at 10:58

0 Answers0