2

I open an existing pdf. Checking for protection and ask for password if it is protected and open it with:

        PdfReader pdfReader = null;
        Stream outputStream = null;
        PdfStamper pdfStamper = null;

        try
        {
            pdfReader = GetPdfReaderObject();
            outputStream = new FileStream(filePathDestination, FileMode.Create, FileAccess.Write, FileShare.None);
            pdfStamper = new PdfStamper(pdfReader, outputStream);

                PdfLayer layer = new PdfLayer("watermark", pdfStamper.Writer);

                for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) {
                    pdfStamper.FormFlattening = false;
                    iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
                    PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);

                    pdfData.BeginLayer(layer);

                    PdfGState graphicsState = new PdfGState();
                    graphicsState.FillOpacity = 0.5F;
                    pdfData.SetGState(graphicsState);
                    pdfData.BeginText();

                    iTextSharp.text.Image watermarkImage = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(watermarkImagePath), ImageFormat.Png);

                    float width = pageRectangle.Width;
                    float height = pageRectangle.Height;

                    watermarkImage.SetAbsolutePosition(width / 2 - watermarkImage.Width / 2, height / 2 - watermarkImage.Height / 2);

                    pdfData.AddImage(watermarkImage);
                    pdfData.EndText();
                    pdfData.EndLayer();
                }
            }
            pdfStamper.Close();
            outputStream.Close();
            outputStream.Dispose();
            pdfReader.Close();
            pdfReader.Dispose();

        } catch (Exception e) {
            ....
        }
    }

After my modifications I save it but the protection is destroyed.

Why the protection is destroyed? How can I save the protection from the origin document und add it to my modified one.

Regards

GermanSniper
  • 249
  • 1
  • 5
  • 19
  • Please provide more code. You don't show your way of modifying your PDF. Do you use a `PdfStamper`? Or a `PdfCopy`? Or a `PdfWriter`? And how? – mkl Oct 24 '13 at 12:17

2 Answers2

3

You use a PdfStamper to manipulate an existing PDF.

For any source PDF: If you want the result to be encrypted, you may use the SetEncryption method appropriately.

Have a look at the EncryptionPdf.cs, especially its method EncryptPdf:

PdfReader reader = ...;
using (MemoryStream ms = new MemoryStream())
{
    using (PdfStamper stamper = new PdfStamper(reader, ms))
    {
        stamper.SetEncryption(
                USER, OWNER, 
                PdfWriter.ALLOW_PRINTING, 
                PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA
        );
    }
    return ms.ToArray();
}

Here USER and OWNER are the user and owner passwords of your choice. You might want to use a different set of permissions.

For already encrypted source PDFs you may alternatively choose to use the PdfStamper in append mode (i.e. use a PdfStamper constructor with a bool append parameter set to true). In that case the original encryption will also be applied to the updated PDF.

mkl
  • 90,588
  • 15
  • 125
  • 265
  • With the append flag the protection/encryption is also working after modification. But if I opeb the pdf with Acrobat Reader it tells me that: "An error exists on this page. Acrobat may not Display the page correctly. Please contact the Person who created the PDF document to correct the Problem". Do I need to encrypt my new added image also? Are what is the problem? On an document with no encryption it's working without failure. – GermanSniper Oct 25 '13 at 06:30
  • @GermanSniper Could you provide a sample, both before and after manipulation? – mkl Oct 25 '13 at 10:13
  • I will provide some sample files later. But one more Problem occours: If I add the tag append I can't remove content from the pdf's. How can I save encryption, delete and add content? Slowly i'm going crazy... – GermanSniper Oct 25 '13 at 11:02
  • 1
    An alternative to using append mode is using the *unethical* mode, cf. the discussion under @Bruno's answer. Simply set the static `bool PdfReader.unethicalreading` to `true` and use your `PdfStamper` without append mode. – mkl Oct 25 '13 at 11:49
  • Here the two sample files with error. I hope u can help me with These. [Sample pdf with error](http://www.file-upload.net/gal-61870/ryg9jw/1.html) – GermanSniper Oct 25 '13 at 16:01
  • I'll look at them later, i don't have my tools available right now. – mkl Oct 26 '13 at 11:23
  • @GermanSniper Ok, I looked at your files (BTW, that file service is quite a pain).The manipulated PDF is not encrypted anymore. Which of the proposed methods did you use to create this PDF? `append`? `unethicalreading`? Explicit separate encryption? – mkl Oct 26 '13 at 23:24
  • oh sry. The files was modified without copy the encryption. Here is an example with encryption. [sample 2 with unethicalreading](http://www.file-upload.net/gal-62249/cyda/1.html) . But always if the source document is encrypted I got an error in my modified pdf document opening with acrobat – GermanSniper Oct 28 '13 at 16:50
  • Ok I solve the Problem with the pdf invalide Content stream. http://stackoverflow.com/questions/8235339/pdf-generated-with-itext-becomes-corrupted-when-using-setsimplecolumn THX for your help!!!!!! – GermanSniper Oct 30 '13 at 06:57
1

Which version of iText are you using?

When a password protected PDF was opened using the owner password and manipulated by PdfStamper, all original password protection was indeed removed. This changed in iText 5.3.5. See the changelog:

Important: we now keep the original owner password when stamping a document.

In other words: with all iText versions prior to 5.3.5, the owner password is lost. Starting with 5.3.5, it should be kept.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • I use version 5.4.3. That can't be the problem – GermanSniper Oct 24 '13 at 13:31
  • *we now keep the original owner password when stamping a document* - Always? I find a `if (reader.isEncrypted() && (append || PdfReader.unethicalreading)) { crypto = new PdfEncryption(reader.getDecrypt()); }` in the `PdfStamperImp` code which looks like keeping it only in append or unethical mode... – mkl Oct 24 '13 at 13:40
  • Hmm... I wrote that code. Now that you remind me of unethical mode, I remember: if you know the owner password, you're probably supposed to set the password with `stamper.setEncryption()`. If we automatically reuse the existing password, there's no way to decrypt a document into an unencrypted PDF (which is also a use-case). I gave an up-vote to your answer (and I also up-voted the question as it's a good one). – Bruno Lowagie Oct 24 '13 at 17:14
  • If i remember Correctly, the check-in comment for adding conditions other than `isEncrypted` was that this made decrypting using the stamper impossible. ;) – mkl Oct 24 '13 at 19:13