Ejemplo n.º 1
0
 public virtual void EncryptWithPasswordAes128EmbeddedFilesOnly()
 {
     String filename = "encryptWithPasswordAes128EmbeddedFilesOnly.pdf";
     int encryptionType = EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.EMBEDDED_FILES_ONLY;
     String outFileName = destinationFolder + filename;
     int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
     PdfWriter writer = new PdfWriter(outFileName, new WriterProperties().SetStandardEncryption(USER, OWNER, permissions
         , encryptionType).AddXmpMetadata());
     PdfDocument document = new PdfDocument(writer);
     document.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
     PdfPage page = document.AddNewPage();
     String textContent = "Hello world!";
     WriteTextBytesOnPageContent(page, textContent);
     String descripton = "encryptedFile";
     String path = sourceFolder + "pageWithContent.pdf";
     document.AddFileAttachment(descripton, PdfFileSpec.CreateEmbeddedFileSpec(document, path, descripton, path
         , null, null));
     page.Flush();
     document.Close();
     //NOTE: Specific crypto filters for EFF StmF and StrF are not supported at the moment. iText don't distinguish objects based on their semantic role
     //      because of this we can't read streams correctly and corrupt such documents on stamping.
     bool ERROR_IS_EXPECTED = true;
     CheckDecryptedWithPasswordContent(destinationFolder + filename, OWNER, textContent, ERROR_IS_EXPECTED);
     CheckDecryptedWithPasswordContent(destinationFolder + filename, USER, textContent, ERROR_IS_EXPECTED);
 }
Ejemplo n.º 2
0
        public void AttachFileiText()
        {
            string inPdf         = "noattach.pdf";
            string sourcePdfFile = Path.Combine(this.pdfRessources, inPdf);
            // Set source and target folders
            string targetFolder = outDir;
            var    method       = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string targetFile   = Path.Combine(targetFolder, string.Concat(DateTime.Now.ToString("yyyyMMdd"), "_" + method + ".pdf"));

            Assert.IsTrue(File.Exists(sourcePdfFile), "Source file doesn't exist");

            if (File.Exists(targetFile))
            {
                File.Delete(targetFile);
            }
            Assert.IsFalse(File.Exists(targetFile));

            WriterProperties propComp = new WriterProperties();

            propComp.SetFullCompressionMode(false);
            propComp.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfWriter   theCompWriter = new PdfWriter(targetFile, propComp);
            PdfDocument origPdf       = new PdfDocument(new PdfReader(sourcePdfFile), theCompWriter);

            Assert.IsNotNull(origPdf);

            PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(origPdf, Encoding.ASCII.GetBytes("Some text in the attached document"), "description of attachment here", "test.txt", null, null, null);

            origPdf.AddFileAttachment("attadescr", spec);
            origPdf.Close();
            Assert.IsTrue(new FileInfo(sourcePdfFile).Length < new FileInfo(targetFile).Length, "target file is not bigger than the source file");
        }
Ejemplo n.º 3
0
        private bool createiText7Pdf(string password = null)
        {
            bool success = false;

            log.Info($"Using iText7 library to create a package with format [{this.packerType}]");
            if (this.overwrite)
            {
                deleteIfExist(this.dstFileName);
            }

            try
            {
                Stream stream = getTemplatePdfStream();
                if (stream == null)
                {
                    log.Error("Could not read the PDF Template from stream");
                    throw new FileNotFoundException("Could not read the PDF template");
                }

                WriterProperties propComp = new WriterProperties();
                propComp.SetFullCompressionMode(true);
                propComp.SetCompressionLevel(CompressionConstants.BEST_COMPRESSION);
                if (String.IsNullOrEmpty(password))
                {
                    log.Warn($"No password was supplied, so the output file will be unencrypted [{this.dstFileName}]");
                }
                else
                {
                    byte[] passwordBytes = Encoding.ASCII.GetBytes(password);
                    propComp.SetStandardEncryption(passwordBytes, passwordBytes, 0, EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
                    log.Info("Enabled PDF AES_256 encryption");
                }
                PdfWriter   theCompWriter = new PdfWriter(this.dstFileName, propComp);
                PdfDocument newPdf        = new PdfDocument(new PdfReader(stream), theCompWriter);
                foreach (string file in this.srcFileList)
                {
                    string      filename = Path.GetFileName(file);
                    PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(
                        newPdf, File.ReadAllBytes(file), filename, filename, null, null, null);
                    newPdf.AddFileAttachment(filename, fileSpec);
                    log.Debug($"Added file '{filename}' as attachment to pdf");
                }
                newPdf.Close();
            }
            catch (Exception e)
            {
                log.Error($"Exception while trying to pack with iText7", e);
                return(false);
            }
            log.Info($"Successfully packed the files into [{this.dstFileName}]");
            return(success);
        }
Ejemplo n.º 4
0
        // This method adds file attachment to the pdf document
        private void AddFileAttachment(PdfDocument document, String attachmentPath, String fileName)
        {
            String embeddedFileName        = fileName;
            String embeddedFileDescription = fileName;
            String fileAttachmentKey       = fileName;

            // the 5th argument is the mime-type of the embedded file;
            // the 6th argument is the AFRelationship key value.
            PdfFileSpec fileSpec = PdfFileSpec.CreateEmbeddedFileSpec(document, attachmentPath, embeddedFileDescription,
                                                                      embeddedFileName, null, null);

            document.AddFileAttachment(fileAttachmentKey, fileSpec);
        }
Ejemplo n.º 5
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

            String embeddedFileName        = "test.txt";
            String embeddedFileDescription = "some_test";

            byte[] embeddedFileContentBytes = Encoding.UTF8.GetBytes("Some test");

            // the 5th argument is the mime-type of the embedded file;
            // the 6th argument is the PdfDictionary containing embedded file's parameters;
            // the 7th argument is the AFRelationship key value.
            PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc, embeddedFileContentBytes,
                                                                  embeddedFileDescription, embeddedFileName, null, null, null);

            // This method adds file attachment at document level.
            pdfDoc.AddFileAttachment("embedded_file", spec);

            pdfDoc.Close();
        }
Ejemplo n.º 6
0
        public virtual void EmbeddedFileAddedInAppendModeTest()
        {
            //Create input document
            MemoryStream boasEmpty      = new MemoryStream();
            PdfWriter    emptyDocWriter = new PdfWriter(boasEmpty);
            PdfDocument  emptyDoc       = new PdfDocument(emptyDocWriter);

            emptyDoc.AddNewPage();
            PdfDictionary emptyNamesDic = new PdfDictionary();

            emptyNamesDic.MakeIndirect(emptyDoc);
            emptyDoc.GetCatalog().GetPdfObject().Put(PdfName.Names, emptyNamesDic);
            emptyDoc.Close();
            //Create input document
            MemoryStream boasAttached    = new MemoryStream();
            PdfWriter    attachDocWriter = new PdfWriter(boasAttached);
            PdfDocument  attachDoc       = new PdfDocument(attachDocWriter);

            attachDoc.AddNewPage();
            attachDoc.Close();
            //Attach file in append mode
            PdfReader    appendReader = new PdfReader(new MemoryStream(boasEmpty.ToArray()));
            MemoryStream boasAppend   = new MemoryStream();
            PdfWriter    appendWriter = new PdfWriter(boasAppend);
            PdfDocument  appendDoc    = new PdfDocument(appendReader, appendWriter, new StampingProperties().UseAppendMode
                                                            ());

            appendDoc.AddFileAttachment("Test File", PdfFileSpec.CreateEmbeddedFileSpec(appendDoc, boasAttached.ToArray
                                                                                            (), "Append Embedded File test", "Test file", null));
            appendDoc.Close();
            //Check final result
            PdfReader   finalReader           = new PdfReader(new MemoryStream(boasAppend.ToArray()));
            PdfDocument finalDoc              = new PdfDocument(finalReader);
            PdfNameTree embeddedFilesNameTree = finalDoc.GetCatalog().GetNameTree(PdfName.EmbeddedFiles);
            IDictionary <String, PdfObject> embeddedFilesMap = embeddedFilesNameTree.GetNames();

            NUnit.Framework.Assert.IsTrue(embeddedFilesMap.Count > 0);
            NUnit.Framework.Assert.IsTrue(embeddedFilesMap.ContainsKey("Test File"));
        }
Ejemplo n.º 7
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

            foreach (String text in ATTACHMENTS)
            {
                String embeddedFileName         = String.Format("{0}.txt", text);
                String embeddedFileDescription  = String.Format("Some test: {0}", text);
                byte[] embeddedFileContentBytes = Encoding.UTF8.GetBytes(embeddedFileDescription);

                // the 5th argument is the mime-type of the embedded file;
                // the 6th argument is the PdfDictionary containing embedded file's parameters;
                // the 7th argument is the AFRelationship key value.
                PdfFileSpec spec = PdfFileSpec.CreateEmbeddedFileSpec(pdfDoc, embeddedFileContentBytes,
                                                                      embeddedFileDescription, embeddedFileName, null, null, null);

                // This method adds file attachment at document level.
                pdfDoc.AddFileAttachment(String.Format("embedded_file{0}", text), spec);
            }

            pdfDoc.Close();
        }