コード例 #1
0
        public virtual void ResolveFontsWithConverterPropsAndWriterProps()
        {
            String                  fileName    = "resolveFonts_WithConverterPropsAndWriterProps";
            String                  svgFile     = "fontSelectorTest";
            WriterProperties        writerprops = new WriterProperties().SetCompressionLevel(0);
            String                  baseUri     = FileUtil.GetParentDirectory(new FileInfo(sourceFolder + svgFile + ".svg"));
            ISvgConverterProperties properties  = new SvgConverterProperties().SetBaseUri(baseUri).SetFontProvider(new
                                                                                                                   BasicFontProvider()).SetMediaDeviceDescription(new MediaDeviceDescription(MediaType.ALL));

            ConvertToSinglePage(new FileStream(sourceFolder + svgFile + ".svg", FileMode.Open, FileAccess.Read), new FileStream
                                    (destinationFolder + fileName + ".pdf", FileMode.Create), properties, writerprops);
            Compare(fileName, sourceFolder, destinationFolder);
        }
コード例 #2
0
        public static void TestDefaultProperties()
        {
            var p = WriterProperties.GetDefaultWriterProperties();

            Assert.AreEqual("parquet-cpp version 1.5.1-SNAPSHOT", p.CreatedBy);
            Assert.AreEqual(1024 * 1024, p.DataPageSize);
            Assert.AreEqual(Encoding.PlainDictionary, p.DictionaryIndexEncoding);
            Assert.AreEqual(Encoding.PlainDictionary, p.DictionaryPageEncoding);
            Assert.AreEqual(1024 * 1024, p.DictionaryPagesizeLimit);
            Assert.AreEqual(64 * 1024 * 1024, p.MaxRowGroupLength);
            Assert.AreEqual(ParquetVersion.PARQUET_1_0, p.Version);
            Assert.AreEqual(1024, p.WriteBatchSize);
        }
コード例 #3
0
 protected override PdfDocument InitDocument(PdfReader reader, PdfWriter writer, StampingProperties properties)
 {
     try
     {
         return(base.InitDocument(reader, writer, properties));
     }
     finally
     {
         FieldInfo        propertiesField  = typeof(PdfWriter).GetField("properties", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
         WriterProperties writerProperties = (WriterProperties)propertiesField.GetValue(writer);
         writerProperties.SetFullCompressionMode(false);
     }
 }
コード例 #4
0
        public void CompressedPdfiText()
        {
            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 targetFileComp   = Path.Combine(targetFolder, string.Concat(DateTime.Now.ToString("yyyyMMdd"), "_" + method + "_compressed.pdf"));
            string targetFileUnComp = Path.Combine(targetFolder, string.Concat(DateTime.Now.ToString("yyyyMMdd"), "_" + method + "_uncompressed.pdf"));

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

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


            // read file
            WriterProperties propComp = new WriterProperties();

            propComp.SetFullCompressionMode(true);
            PdfDocument origPdf = new PdfDocument(new PdfReader(sourcePdfFile), new PdfWriter(targetFileComp, propComp));

            Assert.IsNotNull(origPdf);

            PdfWriter theCompWriter = origPdf.GetWriter();

            origPdf.Close();

            Assert.IsTrue(File.Exists(targetFileComp), "target file comp does not exist");

            // read file
            PdfDocument origPdfAgain = new PdfDocument(new PdfReader(sourcePdfFile), new PdfWriter(targetFileUnComp));

            Assert.IsNotNull(origPdfAgain);
            origPdfAgain.GetWriter().SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfWriter theUncompWriter = origPdfAgain.GetWriter();

            origPdfAgain.Close();

            Assert.IsTrue(File.Exists(targetFileUnComp), "target file uncomp does not exist");

            Assert.IsTrue(new FileInfo(targetFileComp).Length < new FileInfo(targetFileUnComp).Length, "Uncompressed file is not smaller than the compressed file");
        }
コード例 #5
0
ファイル: Encrypter.cs プロジェクト: ravisayal/PDFCreator
        internal void SetEncryption(WriterProperties writerProperties, ConversionProfile profile, JobPasswords jobPasswords)
        {
            if (!profile.PdfSettings.Security.Enabled)
            {
                return;
            }

            var encryption = CalculatePermissionValue(profile);

            _logger.Debug("Calculated Permission Value: " + encryption);

            if (string.IsNullOrEmpty(jobPasswords.PdfOwnerPassword))
            {
                _logger.Error("Launched encryption without owner password.");
                throw new ProcessingException("Launched encryption without owner password.", ErrorCode.Encryption_NoOwnerPassword);
            }

            var ownerPassword = Encoding.Default.GetBytes(jobPasswords.PdfOwnerPassword);

            byte[] userPassword = null;

            if (profile.PdfSettings.Security.RequireUserPassword)
            {
                if (string.IsNullOrEmpty(jobPasswords.PdfUserPassword))
                {
                    _logger.Error("Launched encryption without user password.");
                    throw new ProcessingException("Launched encryption without user password.", ErrorCode.Encryption_NoUserPassword);
                }
                userPassword = Encoding.Default.GetBytes(jobPasswords.PdfUserPassword);
            }

            switch (profile.PdfSettings.Security.EncryptionLevel)
            {
            case EncryptionLevel.Rc40Bit:
                writerProperties.SetStandardEncryption(userPassword, ownerPassword,
                                                       encryption, EncryptionConstants.STANDARD_ENCRYPTION_40);
                break;

            case EncryptionLevel.Rc128Bit:
                writerProperties.SetStandardEncryption(userPassword, ownerPassword,
                                                       encryption, EncryptionConstants.STANDARD_ENCRYPTION_128);
                break;

            case EncryptionLevel.Aes128Bit:
            case EncryptionLevel.Aes256Bit:
                writerProperties.SetStandardEncryption(userPassword, ownerPassword,
                                                       encryption, EncryptionConstants.ENCRYPTION_AES_128);
                break;
            }
        }
コード例 #6
0
        public static void TestDefaultProperties()
        {
            var p = WriterProperties.GetDefaultWriterProperties();

            Assert.AreEqual("parquet-cpp version 1.5.1-SNAPSHOT", p.CreatedBy);
            Assert.AreEqual(Compression.Uncompressed, p.Compression(new ColumnPath("anypath")));
            Assert.AreEqual(int.MinValue, p.CompressionLevel(new ColumnPath("anypath")));
            Assert.AreEqual(1024 * 1024, p.DataPageSize);
            Assert.AreEqual(Encoding.PlainDictionary, p.DictionaryIndexEncoding);
            Assert.AreEqual(Encoding.PlainDictionary, p.DictionaryPageEncoding);
            Assert.AreEqual(1024 * 1024, p.DictionaryPagesizeLimit);
            Assert.AreEqual(64 * 1024 * 1024, p.MaxRowGroupLength);
            Assert.AreEqual(ParquetVersion.PARQUET_1_0, p.Version);
            Assert.AreEqual(1024, p.WriteBatchSize);
        }
コード例 #7
0
        public void ManipulatePdf(string src, string dest)
        {
            WriterProperties writerProperties = new WriterProperties();

            writerProperties.AddXmpMetadata();

            PdfWriter   pdfWriter = new PdfWriter(dest, writerProperties);
            PdfDocument pdfDoc    = new PdfDocument(pdfWriter);

            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));

            pdfDoc.SetTagged();
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));

            PdfDocumentInfo pdfMetaData = pdfDoc.GetDocumentInfo();

            pdfMetaData.SetAuthor("Samuel Huylebroeck");
            pdfMetaData.AddCreationDate();
            pdfMetaData.GetProducer();
            pdfMetaData.SetCreator("iText Software");
            pdfMetaData.SetKeywords("example, accessibility");
            pdfMetaData.SetSubject("PDF accessibility");

            // Title is derived from html

            // pdf conversion
            ConverterProperties props        = new ConverterProperties();
            FontProvider        fontProvider = new FontProvider();

            fontProvider.AddStandardPdfFonts();
            fontProvider.AddDirectory(SRC);

            // The noto-nashk font file (.ttf extension) is placed in the resources
            props.SetFontProvider(fontProvider);
            // Base URI is required to resolve the path to source files
            props.SetBaseUri(SRC);

            // Setup custom tagworker factory for better tagging of headers
            DefaultTagWorkerFactory tagWorkerFactory = new AccessibilityTagWorkerFactory();

            props.SetTagWorkerFactory(tagWorkerFactory);

            HtmlConverter.ConvertToPdf(new FileStream(src, FileMode.Open), pdfDoc, props);

            pdfDoc.Close();
        }
コード例 #8
0
        public MemoryStream CreatePdf(string text)
        {
            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }

            _logger.LogInformation("Creating barcode for '{Text}'", text);

            var properties = new WriterProperties();

            properties.SetPdfVersion(PdfVersion.PDF_1_4);

            var stream = new MemoryStream();

            using var writer = new PdfWriter(stream, properties);
            var pdfDoc = new PdfDocument(writer);

            PdfFont fontOcrb  = PdfFontFactory.CreateFont("wwwroot/OCRB.otf", PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
            Color   cmykBlack = new DeviceCmyk(0, 0, 0, 100);
            var     gState    = new PdfExtGState().SetFillOverPrintFlag(true).SetStrokeOverPrintFlag(true).SetOverprintMode(1);

            var code128 = new Barcode128(pdfDoc);

            code128.SetBaseline(7.67f);
            code128.SetSize(9f);
            code128.SetFont(fontOcrb);
            code128.SetX(0.72f);
            code128.SetBarHeight(14.17f);
            code128.SetCode(text);
            code128.SetCodeType(Barcode128.CODE128);

            var xObject = code128.CreateFormXObject(cmykBlack, cmykBlack, pdfDoc);

            pdfDoc.AddNewPage(new iText.Kernel.Geom.PageSize(xObject.GetWidth(), xObject.GetHeight()));
            PdfCanvas canvas = new PdfCanvas(pdfDoc.GetFirstPage());

            canvas.SaveState();
            canvas.SetExtGState(gState);
            canvas.AddXObjectAt(xObject, 0f, 0f);
            canvas.RestoreState();

            pdfDoc.Close();

            return(stream);
        }
コード例 #9
0
        public byte[] Convert(string htmlContent)
        {
            byte[] pdf = null;
            using (var memoryStream = new MemoryStream())
            {
                var writterProperties = new WriterProperties()
                                        .SetFullCompressionMode(true);
                using (PdfWriter writer = new PdfWriter(memoryStream, writterProperties))
                {
                    PdfDocument pdfDoc = new PdfDocument(writer);
                    pdfDoc.SetTagged();

                    PageSize pageSize = new PageSize(900, 1000);
                    pdfDoc.SetDefaultPageSize(pageSize);

                    ConverterProperties converterProperties = new ConverterProperties();
                    converterProperties.SetCreateAcroForm(true);

                    var fp = new DefaultFontProvider(true, false, false);
                    converterProperties.SetFontProvider(fp);

                    MediaDeviceDescription mediaDescription = new MediaDeviceDescription(MediaType.SCREEN);
                    converterProperties.SetMediaDeviceDescription(mediaDescription);

                    var                elements        = HtmlConverter.ConvertToElements(htmlContent, converterProperties);
                    Document           document        = new Document(pdfDoc);
                    CJKSplitCharacters splitCharacters = new CJKSplitCharacters();
                    document.SetSplitCharacters(splitCharacters);
                    document.SetProperty(Property.SPLIT_CHARACTERS, splitCharacters);
                    foreach (IElement element in elements)
                    {
                        document.Add((IBlockElement)element);
                    }
                    document.Close();

                    pdf = memoryStream.ToArray();

                    memoryStream.Close();
                    pdfDoc.Close();
                }
            }

            return(pdf);
        }
コード例 #10
0
        private void GeneratePDF(MemoryStream file, string ruta, string password)
        {
            string   rutapdf  = Path.ChangeExtension(ruta, ".pdf");
            Workbook workbook = new Workbook();

            workbook.LoadFromStream(file, ExcelVersion.Version2016);

            using (MemoryStream stream = new MemoryStream())
            {
                workbook.SaveToStream(stream, Spire.Xls.FileFormat.PDF);

                PdfReader        reader = new PdfReader(stream);
                WriterProperties props  = new WriterProperties().SetStandardEncryption(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(password), EncryptionConstants.ALLOW_PRINTING,
                                                                                       EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
                PdfWriter   writer = new PdfWriter(rutapdf, props);
                PdfDocument pdfDoc = new PdfDocument(reader, writer);
                pdfDoc.Close();
            }
        }
コード例 #11
0
ファイル: PdfMerge.cs プロジェクト: simonep77/app.pdfutils
        /// <summary>
        /// Avvia merge
        /// </summary>
        /// <param name="name"></param>
        /// <param name="outstream"></param>
        /// <param name="closeOnEndMerge"></param>
        public void BeginMergeToStream(string name, Stream outstream, bool closeOnEndMerge)
        {
            this.NumDocumentsMerged = 0;
            this.NumPagesMerged     = 0;
            this.Name    = name;
            this.mStream = outstream;

            var wp = new WriterProperties().AddXmpMetadata();

            wp.SetPdfVersion(PdfVersion.PDF_1_4);

            var w = new PdfWriter(outstream, wp);

            w.SetCloseStream(closeOnEndMerge);
            w.SetSmartMode(true);

            this.mDocument = new PdfDocument(w);
            this.mMerge    = new PdfMerger(this.mDocument);
        }
コード例 #12
0
 public virtual void EncryptWithPasswordAes128NoMetadataCompression()
 {
     String srcFilename = "srcEncryptWithPasswordAes128NoMetadataCompression.pdf";
     PdfReader reader = new PdfReader(sourceFolder + srcFilename, new ReaderProperties());
     WriterProperties props = new WriterProperties().SetStandardEncryption("superuser".GetBytes(), "superowner"
         .GetBytes(), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants
         .DO_NOT_ENCRYPT_METADATA);
     String outFilename = "encryptWithPasswordAes128NoMetadataCompression.pdf";
     PdfWriter writer = new PdfWriter(destinationFolder + outFilename, props);
     PdfDocument pdfDoc = new PdfDocument(reader, writer);
     pdfDoc.Close();
     CompareTool compareTool = new CompareTool();
     compareTool.EnableEncryptionCompare();
     compareTool.GetOutReaderProperties().SetPassword("superowner".GetBytes());
     compareTool.GetCmpReaderProperties().SetPassword("superowner".GetBytes());
     String outPdf = destinationFolder + outFilename;
     String cmpPdf = sourceFolder + "cmp_" + outFilename;
     NUnit.Framework.Assert.IsNull(compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder, "diff_"));
 }
コード例 #13
0
 /// <exception cref="iText.Kernel.XMP.XMPException"/>
 /// <exception cref="System.IO.IOException"/>
 /// <exception cref="System.Exception"/>
 public virtual void EncryptWithPassword2(String filename, int encryptionType, int compression, bool isPdf2
     )
 {
     int permissions = EncryptionConstants.ALLOW_SCREENREADERS;
     WriterProperties writerProperties = new WriterProperties().SetStandardEncryption(USER, OWNER, permissions,
         encryptionType);
     if (isPdf2) {
         writerProperties.SetPdfVersion(PdfVersion.PDF_2_0);
     }
     PdfWriter writer = new PdfWriter(destinationFolder + filename, writerProperties.AddXmpMetadata());
     writer.SetCompressionLevel(compression);
     PdfDocument document = new PdfDocument(writer);
     document.GetDocumentInfo().SetMoreInfo(customInfoEntryKey, customInfoEntryValue);
     PdfPage page = document.AddNewPage();
     WriteTextBytesOnPageContent(page, pageTextContent);
     page.Flush();
     document.Close();
     CompareEncryptedPdf(filename);
     CheckEncryptedWithPasswordDocumentStamping(filename, OWNER);
     CheckEncryptedWithPasswordDocumentAppending(filename, OWNER);
 }
コード例 #14
0
        public static void EncryptPdf(string password)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                PdfReader        pdfReader        = new PdfReader(new MemoryStream(PdfFile));
                byte[]           ownerPassword    = System.Text.Encoding.Default.GetBytes(password);
                WriterProperties writerProperties = new WriterProperties();
                writerProperties.SetStandardEncryption(ownerPassword, ownerPassword, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_256);

                PdfWriter   pdfWriter   = new PdfWriter(stream, writerProperties);
                PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);

                pdfDocument.Close();
                pdfReader.Close();
                pdfWriter.Close();

                FinalEncryptedPdfURL = Format + Convert.ToBase64String(stream.ToArray());
            }

            IsSubmitComplete     = true;
            IsEncryptionComplete = true;
        }
コード例 #15
0
        public virtual void ImgAttrAlignLeftReadOrderPdfTest()
        {
            String           pdfDestinationFile    = destinationFolder + "imgAttrAlignLeftReadOrderPdf.pdf";
            String           htmlSource            = sourceFolder + "imgAttrAlignLeftReadOrderPdf.html";
            String           cmpPdfDestinationFile = sourceFolder + "cmp_imgAttrAlignLeftReadOrderPdf.pdf";
            FileStream       fileOutputStream      = new FileStream(pdfDestinationFile, FileMode.Create);
            WriterProperties writerProperties      = new WriterProperties();

            writerProperties.AddXmpMetadata();
            PdfWriter   pdfWriter   = new PdfWriter(fileOutputStream, writerProperties);
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);

            pdfDocument.GetCatalog().SetLang(new PdfString("en-US"));
            pdfDocument.SetTagged();
            ConverterProperties converterProperties = new ConverterProperties();

            converterProperties.SetBaseUri(sourceFolder);
            FileStream fileInputStream = new FileStream(htmlSource, FileMode.Open, FileAccess.Read);

            HtmlConverter.ConvertToPdf(fileInputStream, pdfDocument, converterProperties);
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(pdfDestinationFile, cmpPdfDestinationFile
                                                                             , destinationFolder));
        }
コード例 #16
0
        //Metódo criado para criptografar o PDF usando iText.Kerner.Pdf
        static void Encrypt(string file)
        {
            byte[] ownerPass = Encoding.ASCII.GetBytes("123456");
            // definindo a senha que será necessária para abrir o documento
            byte[] userPass = Encoding.ASCII.GetBytes("123");
            // recebendo o arquivo para a criptografia
            using (Stream input = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                //definido o diretório e o nome do arquivo que ficara salvo o novo PDF protegido
                using (Stream output = new FileStream(@"D:\ALGORIX DEMANDAS E PROJETOS\TestProtected.pdf", FileMode.Create,
                                                      FileAccess.Write, FileShare.None))
                {
                    var pdfReader = new PdfReader(input);
                    Console.WriteLine("Carregado arquivo {0}", file);
                    WriterProperties props = new WriterProperties().SetStandardEncryption(userPass, ownerPass,
                                                                                          EncryptionConstants.ALLOW_PRINTING,
                                                                                          EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA
                                                                                          );

                    var writer      = new PdfWriter(output, props);
                    var pdfDocument = new PdfDocument(pdfReader, writer);
                    pdfDocument.Close();
                }
        }
コード例 #17
0
        private void btnPDF_Click(object sender, EventArgs e)
        {
            // Source File
            string sourceFile = txtFilePath.Text;
            // New filename
            string newNonSecureFile = sourceFile.Substring(0, sourceFile.Length - 4) + " - Non-Secure.pdf";
            // New secure file
            string newSecureFile = sourceFile.Substring(0, sourceFile.Length - 4) + " - Secure.pdf";

            //Initialize PDF document
            PdfDocument pdfDoc   = new PdfDocument(new PdfReader(sourceFile), new PdfWriter(newNonSecureFile));
            Document    document = new Document(pdfDoc);
            Rectangle   pageSize;
            int         n = pdfDoc.GetNumberOfPages();

            for (int i = 1; i <= n; i++)
            {
                PdfPage page = pdfDoc.GetPage(i);
                pageSize = page.GetPageSize();
                //Draw watermark
                Paragraph paragraph = new Paragraph(txtWatermark.Text).SetFontSize(30);
                PdfCanvas over      = new PdfCanvas(pdfDoc.GetPage(i).NewContentStreamBefore(), new PdfResources(), pdfDoc);

                // Watermark color selection
                if (rbRed.Checked == true)
                {
                    over.SetFillColor(ColorConstants.RED);
                }
                else if (rbOrange.Checked == true)
                {
                    over.SetFillColor(ColorConstants.ORANGE);
                }
                else if (rbBlue.Checked == true)
                {
                    over.SetFillColor(ColorConstants.BLUE);
                }
                else if (rbBlack.Checked == true)
                {
                    over.SetFillColor(ColorConstants.BLACK);
                }
                else
                {
                    over.SetFillColor(ColorConstants.MAGENTA);
                }
                over.SaveState();
                Canvas canvasWatermark1 = new Canvas(over, pdfDoc.GetDefaultPageSize())
                                          .ShowTextAligned(paragraph, pageSize.GetWidth() / 2, pageSize.GetHeight() / 2, pdfDoc.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
                canvasWatermark1.Close();

                // Creating a dictionary that maps resource names to graphics state parameter dictionaries

                PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.2f);
                over.SetExtGState(gs1);
                over.RestoreState();
            }
            pdfDoc.Close();

            // Secure PDF file
            PdfReader        pdfReader        = new PdfReader(newNonSecureFile);
            WriterProperties writerProperties = new WriterProperties();

            writerProperties.SetStandardEncryption(USERPASS, OWNERPASS, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128);
            PdfWriter   pdfWriter   = new PdfWriter(new FileStream(newSecureFile, FileMode.Create), writerProperties);
            PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);

            pdfDocument.Close();

            // Messagebox to show completed
            MessageBox.Show("Secure PDF Completed!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

            // Open PDF on completion
            if (chkOpen.Checked == true)
            {
                Process.Start(newSecureFile);
            }
            else
            {
                return;
            }

            // Delete non secure version of file
            File.Delete(newNonSecureFile);
        }
コード例 #18
0
        public virtual void ConvertToSinglePage(Stream svg, Stream pdfOutputStream)
        {
            WriterProperties writerprops = new WriterProperties().SetCompressionLevel(0);

            SvgConverter.CreatePdf(svg, pdfOutputStream, writerprops);
        }
コード例 #19
0
 public virtual void ConvertToSinglePage(Stream svg, Stream pdfOutputStream, ISvgConverterProperties properties
                                         , WriterProperties writerprops)
 {
     SvgConverter.CreatePdf(svg, pdfOutputStream, properties, writerprops);
 }
コード例 #20
0
 public virtual void ConvertToSinglePage(FileInfo svg, FileInfo pdf, WriterProperties writerProperties)
 {
     SvgConverter.CreatePdf(svg, pdf, writerProperties);
 }
コード例 #21
0
ファイル: frmMain.cs プロジェクト: fortrieb/PDFEncrypt
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            // Clean up text
            txtInputFile.Text  = txtInputFile.Text.Trim();
            txtOutputFile.Text = txtOutputFile.Text.Trim();

            // Ensure input and output are not the same.
            if (txtInputFile.Text.ToLower() == txtOutputFile.Text.ToLower())
            {
                MessageBox.Show("Source and Destination files cannot be the same.", "Invalid source/destination", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtOutputFile.Focus();
                txtOutputFile.SelectAll();
                return;
            }

            // Ensure input file exists.
            if (!File.Exists(txtInputFile.Text))
            {
                MessageBox.Show("Source file does not exist.");
                txtInputFile.Focus();
                txtInputFile.SelectAll();
                return;
            }

            // If output file exists, prompt to overwrite.
            if (File.Exists(txtOutputFile.Text))
            {
                if (MessageBox.Show("Destination file already exists.  Overwrite this file?", "Overwrite file?", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    txtOutputFile.Focus();
                    txtOutputFile.SelectAll();
                    return;
                }
            }

            // Verify password:
            if (txtPassword.Text == "")
            {
                MessageBox.Show("No password specified.");
                txtPassword.Focus();
                return;
            }

            // Confirm password:
            if (Settings.password_confirm)
            {
                var input = new frmInputBox();
                input.prompt = "Please retype the password to confirm.";
                input.title  = "Confirm password";
                input.ShowDialog();                     // Modal, blocking call

                if (input.cancelled)
                {
                    return;
                }

                // If password doesn't match, stop.
                if (input.result != txtPassword.Text)
                {
                    MessageBox.Show("Password does not match. Please retry.");
                    return;
                }
            }

            // See https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-protect-already-existing-pdf-password
            try
            {
                // Set mouse cursor to wait.
                Cursor.Current = Cursors.WaitCursor;
                Application.DoEvents();

                // Encryption properties:
                int encryption_properties = (int)Settings.encryption_type;

                // If specified, disable encrypting metadata.
                if (!Settings.encrypt_metadata)
                {
                    encryption_properties |= EncryptionConstants.DO_NOT_ENCRYPT_METADATA;
                }

                // Set document options
                int document_options = 0;
                if (Settings.allow_printing)
                {
                    document_options |= EncryptionConstants.ALLOW_PRINTING;
                }
                if (Settings.allow_degraded_printing)
                {
                    document_options |= EncryptionConstants.ALLOW_DEGRADED_PRINTING;
                }
                if (Settings.allow_modifying)
                {
                    document_options |= EncryptionConstants.ALLOW_MODIFY_CONTENTS;
                }
                if (Settings.allow_modifying_annotations)
                {
                    document_options |= EncryptionConstants.ALLOW_MODIFY_ANNOTATIONS;
                }
                if (Settings.allow_copying)
                {
                    document_options |= EncryptionConstants.ALLOW_COPY;
                }
                if (Settings.allow_form_fill)
                {
                    document_options |= EncryptionConstants.ALLOW_FILL_IN;
                }
                if (Settings.allow_assembly)
                {
                    document_options |= EncryptionConstants.ALLOW_ASSEMBLY;
                }
                if (Settings.allow_screenreaders)
                {
                    document_options |= EncryptionConstants.ALLOW_SCREENREADERS;
                }

                PdfReader        reader = new PdfReader(txtInputFile.Text);                                                           // Create a PdfReader with the input file.
                WriterProperties prop   = new WriterProperties();                                                                     // Set properties of output
                prop.SetStandardEncryption(Encoding.ASCII.GetBytes(txtPassword.Text), null, document_options, encryption_properties); // Enable encryption
                // Setting Owner Password to null generates random password.

                PdfWriter   writer = new PdfWriter(txtOutputFile.Text, prop); // Set up the output file
                PdfDocument pdf    = new PdfDocument(reader, writer);         // Create the new document
                pdf.Close();                                                  // Close the output document.
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while processing the file: " + ex.Message);
                Cursor.Current = Cursors.Default;
                return;
            }

            // If launching a program:
            if (Settings.run_after)
            {
                // Attempt to run the program, passing the newly encrypted filename.
                Process.Start(Settings.run_after_file, txtOutputFile.Text);
            }

            // If opening the output file:
            if (Settings.open_after)
            {
                // Attempt to launch the default app for the file.
                Process.Start(txtOutputFile.Text);
            }

            // If launching Explorer:
            if (Settings.show_folder_after)
            {
                // Attempt to launch the folder with the file highlighted.
                Process.Start("explorer.exe", "/select," + txtOutputFile.Text);
            }

            // If closing after encryption
            if (Settings.close_after)
            {
                this.Close();
            }

            Cursor.Current = Cursors.Default;                   // Return to default cursor.
        }