Example #1
0
        public virtual void TestNoExtraNoise()
        {
            Directory             dir = NewDirectory();
            IndexWriter           writer;
            IndexWriterConfig     c                     = new IndexWriterConfig(TEST_VERSION_CURRENT, new ThrowingAnalyzer());
            ByteArrayOutputStream infoBytes             = new ByteArrayOutputStream();
            StreamWriter          infoPrintStream       = new StreamWriter(infoBytes, Encoding.UTF8);
            TextWriterInfoStream  printStreamInfoStream = new TextWriterInfoStream(infoPrintStream);

            c.SetInfoStream(printStreamInfoStream);
            writer = new IndexWriter(dir, c);
            Document doc = new Document();

            doc.Add(NewField("boringFieldName", "aaa ", storedTextType));
            try
            {
                writer.AddDocument(doc);
            }
#pragma warning disable 168
            catch (BadNews badNews)
#pragma warning restore 168
            {
                Assert.Fail("Unwanted exception");
            }
            infoPrintStream.Flush();
            string infoStream = Encoding.UTF8.GetString(infoBytes.ToArray());
            Assert.IsFalse(infoStream.Contains("boringFieldName"));

            writer.Dispose();
            dir.Dispose();
        }
 public virtual void CopyPagesWithOCGSameObject()
 {
     byte[] docBytes;
     using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
         using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) {
             PdfPage       page        = document.AddNewPage();
             PdfResources  pdfResource = page.GetResources();
             PdfDictionary ocg         = new PdfDictionary();
             ocg.Put(PdfName.Type, PdfName.OCG);
             ocg.Put(PdfName.Name, new PdfString("name1"));
             ocg.MakeIndirect(document);
             pdfResource.AddProperties(ocg);
             PdfPage      page2        = document.AddNewPage();
             PdfResources pdfResource2 = page2.GetResources();
             pdfResource2.AddProperties(ocg);
             document.GetCatalog().GetOCProperties(true);
         }
         docBytes = outputStream.ToArray();
     }
     using (PdfDocument outDocument = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()))) {
         using (PdfDocument fromDocument = new PdfDocument(new PdfReader(new MemoryStream(docBytes)))) {
             fromDocument.CopyPagesTo(1, fromDocument.GetNumberOfPages(), outDocument);
         }
         IList <String> layerNames = new List <String>();
         layerNames.Add("name1");
         PdfDocumentUnitTest.AssertLayerNames(outDocument, layerNames);
     }
 }
Example #3
0
        /// <summary>
        /// Decompress the byte array previously returned by
        ///  compress
        /// </summary>
        public static byte[] Decompress(sbyte[] value, int offset, int length)
        {
            // Create an expandable byte array to hold the decompressed data
            ByteArrayOutputStream bos = new ByteArrayOutputStream(length);

            Inflater decompressor = SharpZipLib.CreateInflater();

            try
            {
                decompressor.SetInput((byte[])(Array)value);

                // Decompress the data
                byte[] buf = new byte[1024];
                while (!decompressor.IsFinished)
                {
                    int count = decompressor.Inflate(buf);
                    bos.Write(buf, 0, count);
                }
            }
            finally
            {
            }

            return(bos.ToArray());
        }
Example #4
0
        public virtual void TestInfoStreamGetsFieldName()
        {
            Directory             dir = NewDirectory();
            IndexWriter           writer;
            IndexWriterConfig     c                     = new IndexWriterConfig(TEST_VERSION_CURRENT, new ThrowingAnalyzer());
            ByteArrayOutputStream infoBytes             = new ByteArrayOutputStream();
            StreamWriter          infoPrintStream       = new StreamWriter(infoBytes, Encoding.UTF8);
            TextWriterInfoStream  printStreamInfoStream = new TextWriterInfoStream(infoPrintStream);

            c.SetInfoStream(printStreamInfoStream);
            writer = new IndexWriter(dir, c);
            Document doc = new Document();

            doc.Add(NewField("distinctiveFieldName", "aaa ", storedTextType));
            try
            {
                writer.AddDocument(doc);
                Assert.Fail("Failed to fail.");
            }
            catch (BadNews)
            {
                infoPrintStream.Flush();
                string infoStream = Encoding.UTF8.GetString(infoBytes.ToArray());
                Assert.IsTrue(infoStream.Contains("distinctiveFieldName"));
            }

            writer.Dispose();
            dir.Dispose();
        }
Example #5
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument       pdfDoc     = new PdfDocument(new PdfWriter(dest));
            PdfPageFormCopier formCopier = new PdfPageFormCopier();

            // Initialize an outline tree of the document and sets outline mode to true
            pdfDoc.InitializeOutlines();

            using (StreamReader streamReader = new StreamReader(DATA))
            {
                // Read first line with headers,
                // do nothing with this line, because headers are already filled in form
                String line = streamReader.ReadLine();

                while ((line = streamReader.ReadLine()) != null)
                {
                    // Create a PDF in memory
                    ByteArrayOutputStream baos        = new ByteArrayOutputStream();
                    PdfDocument           pdfInnerDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                    PdfAcroForm           form        = PdfAcroForm.GetAcroForm(pdfInnerDoc, true);

                    // Parse text line and fill all fields of form
                    FillAndFlattenForm(line, form);
                    pdfInnerDoc.Close();

                    // Copy page with current filled form to the result pdf document
                    pdfInnerDoc = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
                    pdfInnerDoc.CopyPagesTo(1, pdfInnerDoc.GetNumberOfPages(), pdfDoc, formCopier);
                    pdfInnerDoc.Close();
                }
            }

            pdfDoc.Close();
        }
Example #6
0
        public virtual void CopySelfContainedObject()
        {
            ByteArrayOutputStream inputBytes        = new ByteArrayOutputStream();
            PdfDocument           prepInputDoc      = new PdfDocument(new PdfWriter(inputBytes));
            PdfDictionary         selfContainedDict = new PdfDictionary();
            PdfName randDictName = PdfName.Sound;
            PdfName randEntry1   = PdfName.R;
            PdfName randEntry2   = PdfName.S;

            selfContainedDict.Put(randEntry1, selfContainedDict);
            selfContainedDict.Put(randEntry2, selfContainedDict);
            prepInputDoc.AddNewPage().Put(randDictName, selfContainedDict.MakeIndirect(prepInputDoc));
            prepInputDoc.Close();
            PdfDocument srcDoc  = new PdfDocument(new PdfReader(new MemoryStream(inputBytes.ToArray())));
            PdfDocument destDoc = new PdfDocument(new PdfWriter(destinationFolder + "copySelfContainedObject.pdf"));

            srcDoc.CopyPagesTo(1, 1, destDoc);
            PdfDictionary destPageObj            = destDoc.GetFirstPage().GetPdfObject();
            PdfDictionary destSelfContainedDict  = destPageObj.GetAsDictionary(randDictName);
            PdfDictionary destSelfContainedDictR = destSelfContainedDict.GetAsDictionary(randEntry1);
            PdfDictionary destSelfContainedDictS = destSelfContainedDict.GetAsDictionary(randEntry2);

            NUnit.Framework.Assert.AreEqual(destSelfContainedDict.GetIndirectReference(), destSelfContainedDictR.GetIndirectReference
                                                ());
            NUnit.Framework.Assert.AreEqual(destSelfContainedDict.GetIndirectReference(), destSelfContainedDictS.GetIndirectReference
                                                ());
            destDoc.Close();
            srcDoc.Close();
        }
Example #7
0
        /// <summary>
        /// Compresses the specified byte range using the
        ///  specified compressionLevel (constants are defined in
        ///  java.util.zip.Deflater).
        /// </summary>
        public static byte[] Compress(sbyte[] value, int offset, int length, int compressionLevel)
        {
            /* Create an expandable byte array to hold the compressed data.
             * You cannot use an array that's the same size as the orginal because
             * there is no guarantee that the compressed data will be smaller than
             * the uncompressed data. */
            ByteArrayOutputStream bos = new ByteArrayOutputStream(length);

            Deflater compressor = SharpZipLib.CreateDeflater();

            try
            {
                compressor.SetLevel(compressionLevel);
                compressor.SetInput((byte[])(Array)value, offset, length);
                compressor.Finish();

                // Compress the data
                var buf = new byte[1024];
                while (!compressor.IsFinished)
                {
                    int count = compressor.Deflate(buf);
                    bos.Write(buf, 0, count);
                }
            }
            finally
            {
            }

            return(bos.ToArray());
        }
        public virtual byte[] CreatePartiallyFlattenedForm()
        {
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfDocument           pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
            Document    doc  = new Document(pdfDoc);
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, false);

            IDictionary <String, PdfFormField> fields = form.GetFormFields();

            fields["sunday_1"].SetValue("1");
            fields["sunday_2"].SetValue("2");
            fields["sunday_3"].SetValue("3");
            fields["sunday_4"].SetValue("4");
            fields["sunday_5"].SetValue("5");
            fields["sunday_6"].SetValue("6");

            // Add the fields, identified by name, to the list of fields to be flattened
            form.PartialFormFlattening("sunday_1");
            form.PartialFormFlattening("sunday_2");
            form.PartialFormFlattening("sunday_3");
            form.PartialFormFlattening("sunday_4");
            form.PartialFormFlattening("sunday_5");
            form.PartialFormFlattening("sunday_6");

            // Only the included above fields are flattened.
            // If no fields have been explicitly included, then all fields are flattened.
            form.FlattenFields();

            doc.Close();

            return(baos.ToArray());
        }
Example #9
0
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            //read src file
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfDocument           pdfDoc = new PdfDocument(new PdfReader(Path.GetFullPath(SRC)), new PdfWriter(baos));

            //genetate pdf form fields
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, false);

            PropertyInfo[] properties = Pdf.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (property.GetValue(Pdf, null) == null)
                {
                    continue;
                }

                //field name
                string name = property.Name;
                //field value
                string value         = "";
                string propertyValue = property.GetValue(Pdf, null).ToString();
                switch (property.Name)
                {
                case "Dob":
                    //date of birth
                    value = DateTime.Parse(propertyValue).ToString("dd/MMM/yyyy");
                    break;

                case "Restatus":
                    //relationship status
                    name  = RelationshipStatus(propertyValue);
                    value = "yes";
                    form.GetField(name).SetCheckType(1);
                    break;

                default:
                    value = propertyValue;
                    break;
                }
                //set field name
                form.GetField(name).SetValue(value);
            }

            //flat form
            form.FlattenFields();

            pdfDoc.Close();

            return(File(baos.ToArray(), "application/pdf", "result.pdf"));
        }
Example #10
0
        /// <summary>Load data from URL.</summary>
        /// <remarks>
        /// Load data from URL. url must be not null.
        /// Note, this method doesn't check if data or url is null.
        /// </remarks>
        /// <exception cref="System.IO.IOException"/>
        internal virtual void LoadData()
        {
            RandomAccessFileOrArray raf = new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateSource(url
                                                                                                                   ));
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            StreamUtil.TransferBytes(raf, stream);
            raf.Close();
            data = stream.ToArray();
        }
Example #11
0
        protected byte[] RenameFields(String src, int i)
        {
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfDocument           pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(baos));

            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);

            foreach (PdfFormField field in form.GetFormFields().Values)
            {
                field.SetFieldName(String.Format("{0}_{1}", field.GetFieldName().ToString(), i));
            }

            pdfDoc.Close();

            return(baos.ToArray());
        }
Example #12
0
        public virtual byte[] CreateForm()
        {
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfDocument           pdfDoc = new PdfDocument(new PdfWriter(baos));
            Rectangle             rect   = new Rectangle(36, 720, 108, 86);

            PdfTextFormField textFormField = PdfFormField.CreateText(pdfDoc, rect, FIELD_NAME, "text");

            // Being set as true, the field can contain multiple lines of text;
            // if false, the field's text is restricted to a single line.
            textFormField.SetMultiline(true);
            PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(textFormField);

            pdfDoc.Close();

            return(baos.ToArray());
        }
Example #13
0
        /// <summary>Load data by URL.</summary>
        /// <remarks>
        /// Load data by URL. url must be not null.
        /// Note, this method doesn't check if data or url is null.
        /// </remarks>
        internal virtual void LoadData()
        {
            Stream input = null;

            try {
                input = UrlUtil.OpenStream(url);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                StreamUtil.TransferBytes(UrlUtil.OpenStream(url), stream);
                data = stream.ToArray();
            }
            finally {
                if (input != null)
                {
                    input.Dispose();
                }
            }
        }
Example #14
0
        public HttpResponseMessage Combine(List <PDF> pdfs)
        {
            string        ret         = "";
            List <byte[]> sourceFiles = new List <byte[]>();

            foreach (PDF pdf in pdfs)
            {
                ret += pdf.Name + ";";
                sourceFiles.Add(System.IO.File.ReadAllBytes(pdf.FullPath));
            }
            using (ByteArrayOutputStream baos = new ByteArrayOutputStream())
            {
                PdfDocument doc    = new PdfDocument(new PdfWriter(baos));
                PdfMerger   merger = new PdfMerger(doc);

                foreach (var pdf in pdfs)
                {
                    PdfDocument tmpDoc = new PdfDocument(new PdfReader(pdf.FullPath));
                    merger.Merge(tmpDoc, 1, tmpDoc.GetNumberOfPages());
                    tmpDoc.Close();
                }

                merger.Close();
                doc.Close();

                using (MemoryStream ms = new MemoryStream(baos.ToArray()))
                {
                    using (FileStream file = new FileStream("p2.pdf", FileMode.Create))
                        ms.CopyTo(file);
                    var pushStreamContent = new PushStreamContent((outputstream, cotent, context) =>
                    {
                        ms.Position = 0;
                        ms.CopyTo(outputstream);
                        ms.Dispose();
                        outputstream.Close();
                    }, "application/pdf");
                    return(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = pushStreamContent
                    });
                }
            }
        }
 private static byte[] InitDocument(IList <String> names)
 {
     using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
         using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) {
             PdfPage      page        = document.AddNewPage();
             PdfResources pdfResource = page.GetResources();
             foreach (String name in names)
             {
                 PdfDictionary ocg = new PdfDictionary();
                 ocg.Put(PdfName.Type, PdfName.OCG);
                 ocg.Put(PdfName.Name, new PdfString(name));
                 ocg.MakeIndirect(document);
                 pdfResource.AddProperties(ocg);
             }
             document.GetCatalog().GetOCProperties(true);
         }
         return(outputStream.ToArray());
     }
 }
Example #16
0
        public byte[] CreateForm()
        {
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfDocument           pdfDoc = new PdfDocument(new PdfWriter(baos));
            PdfFont     font             = PdfFontFactory.CreateFont();
            PdfAcroForm form             = PdfAcroForm.GetAcroForm(pdfDoc, true);

            Rectangle        rect      = new Rectangle(36, 770, 104, 36);
            PdfTextFormField textField = PdfFormField.CreateText(pdfDoc, rect, "text",
                                                                 "text", font, 20f);

            // Being set as true, the field can contain multiple lines of text;
            // if false, the field's text is restricted to a single line.
            textField.SetMultiline(true);
            form.AddField(textField);

            pdfDoc.Close();

            return(baos.ToArray());
        }
        protected void ManipulatePdf(String dest)
        {
            PdfWriter         writer     = new PdfWriter(dest);
            PdfPageFormCopier formCopier = new PdfPageFormCopier();

            // In smart mode when resources (such as fonts, images,...) are encountered,
            // a reference to these resources is saved in a cache and can be reused.
            // This mode reduces the file size of the resulting PDF document.
            writer.SetSmartMode(true);
            PdfDocument pdfDoc = new PdfDocument(writer);

            // Initialize an outline tree of the document and sets outline mode to true
            pdfDoc.InitializeOutlines();

            using (StreamReader streamReader = new StreamReader(DATA))
            {
                // Read first line with headers,
                // do nothing with this line, because headers are already filled in form
                String line = streamReader.ReadLine();

                while ((line = streamReader.ReadLine()) != null)
                {
                    // Сreate a PDF in memory
                    ByteArrayOutputStream baos        = new ByteArrayOutputStream();
                    PdfDocument           pdfInnerDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                    PdfAcroForm           form        = PdfAcroForm.GetAcroForm(pdfInnerDoc, true);

                    // Parse text line and fill all fields of form
                    FillAndFlattenForm(line, form);
                    pdfInnerDoc.Close();

                    // Copy page with current filled form to the result pdf document
                    pdfInnerDoc = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
                    pdfInnerDoc.CopyPagesTo(1, pdfInnerDoc.GetNumberOfPages(), pdfDoc, formCopier);
                    pdfInnerDoc.Close();
                }
            }

            pdfDoc.Close();
        }
        private PdfObject GenerateWidthsArray()
        {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            OutputStream <ByteArrayOutputStream> stream = new OutputStream <ByteArrayOutputStream>(bytes);

            stream.WriteByte('[');
            int  lastNumber = -10;
            bool firstTime  = true;

            foreach (int code in longTag)
            {
                Glyph glyph = fontProgram.GetGlyphByCode(code);
                if (glyph.GetWidth() == FontProgram.DEFAULT_WIDTH)
                {
                    continue;
                }
                if (glyph.GetCode() == lastNumber + 1)
                {
                    stream.WriteByte(' ');
                }
                else
                {
                    if (!firstTime)
                    {
                        stream.WriteByte(']');
                    }
                    firstTime = false;
                    stream.WriteInteger(glyph.GetCode());
                    stream.WriteByte('[');
                }
                stream.WriteInteger(glyph.GetWidth());
                lastNumber = glyph.GetCode();
            }
            if (stream.GetCurrentPos() > 1)
            {
                stream.WriteString("]]");
                return(new PdfLiteral(bytes.ToArray()));
            }
            return(null);
        }
Example #19
0
        public virtual void InlineImagesTest02()
        {
            String                filename = "inlineImages02.pdf";
            PdfDocument           document = new PdfDocument(new PdfWriter(destinationFolder + filename));
            PdfPage               page     = document.AddNewPage();
            PdfCanvas             canvas   = new PdfCanvas(page);
            Stream                stream   = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "Desert.jpg"));
            ByteArrayOutputStream baos     = new ByteArrayOutputStream();

            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 700, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "bulb.gif"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 600, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "smpl.bmp"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 500, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "itext.png"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 460, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "0047478.jpg"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 300, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "map.jp2"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 200, 100, true);
            stream = UrlUtil.OpenStream(UrlUtil.ToURL(sourceFolder + "amb.jb2"));
            baos   = new ByteArrayOutputStream();
            StreamUtil.TransferBytes(stream, baos);
            canvas.AddImage(ImageDataFactory.Create(baos.ToArray()), 36, 30, 100, true);
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + filename, sourceFolder
                                                                             + "cmp_" + filename, destinationFolder));
        }
Example #20
0
        public virtual void ColorTest04()
        {
            //Create document with 3 colored rectangles in memory.
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfWriter             writer = new PdfWriter(baos);

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document   = new PdfDocument(writer);
            PdfPage     page       = document.AddNewPage();
            PdfCanvas   canvas     = new PdfCanvas(page);
            FileStream  streamGray = new FileStream(SOURCE_FOLDER + "BlackWhite.icc", FileMode.Open, FileAccess.Read);
            FileStream  streamRgb  = new FileStream(SOURCE_FOLDER + "CIERGB.icc", FileMode.Open, FileAccess.Read);
            FileStream  streamCmyk = new FileStream(SOURCE_FOLDER + "USWebUncoated.icc", FileMode.Open, FileAccess.Read
                                                    );
            IccBased gray = new IccBased(streamGray, new float[] { 0.5f });
            IccBased rgb  = new IccBased(streamRgb, new float[] { 1.0f, 0.5f, 0f });
            IccBased cmyk = new IccBased(streamCmyk, new float[] { 1.0f, 0.5f, 0f, 0f });

            canvas.SetFillColor(gray).Rectangle(50, 500, 50, 50).Fill();
            canvas.SetFillColor(rgb).Rectangle(150, 500, 50, 50).Fill();
            canvas.SetFillColor(cmyk).Rectangle(250, 500, 50, 50).Fill();
            canvas.Release();
            document.Close();
            //Copies page from created document to new document.
            //This is not strictly necessary for ICC-based colors paces test, but this is an additional test for copy functionality.
            byte[]    bytes  = baos.ToArray();
            PdfReader reader = new PdfReader(new MemoryStream(bytes));

            document = new PdfDocument(reader);
            writer   = new PdfWriter(DESTINATION_FOLDER + "colorTest04.pdf");
            PdfDocument newDocument = new PdfDocument(writer);

            newDocument.AddPage(document.GetPage(1).CopyTo(newDocument));
            newDocument.Close();
            document.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + "colorTest04.pdf", SOURCE_FOLDER
                                                                             + "cmp_colorTest04.pdf", DESTINATION_FOLDER, "diff_"));
        }
        public virtual void CopyPagesFlushedResources()
        {
            byte[] docBytes;
            using (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                using (PdfDocument document = new PdfDocument(new PdfWriter(outputStream))) {
                    PdfPage       page        = document.AddNewPage();
                    PdfResources  pdfResource = page.GetResources();
                    PdfDictionary ocg         = new PdfDictionary();
                    ocg.Put(PdfName.Type, PdfName.OCG);
                    ocg.Put(PdfName.Name, new PdfString("name1"));
                    ocg.MakeIndirect(document);
                    pdfResource.AddProperties(ocg);
                    pdfResource.MakeIndirect(document);
                    PdfPage page2 = document.AddNewPage();
                    page2.SetResources(pdfResource);
                    document.GetCatalog().GetOCProperties(true);
                }
                docBytes = outputStream.ToArray();
            }
            PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());

            using (PdfDocument outDocument = new PdfDocument(writer)) {
                using (PdfDocument fromDocument = new PdfDocument(new PdfReader(new MemoryStream(docBytes)))) {
                    fromDocument.CopyPagesTo(1, 1, outDocument);
                    IList <String> layerNames = new List <String>();
                    layerNames.Add("name1");
                    PdfDocumentUnitTest.AssertLayerNames(outDocument, layerNames);
                    outDocument.FlushCopiedObjects(fromDocument);
                    fromDocument.CopyPagesTo(2, 2, outDocument);
                    NUnit.Framework.Assert.IsNotNull(outDocument.GetCatalog());
                    PdfOCProperties ocProperties = outDocument.GetCatalog().GetOCProperties(false);
                    NUnit.Framework.Assert.IsNotNull(ocProperties);
                    NUnit.Framework.Assert.AreEqual(1, ocProperties.GetLayers().Count);
                    PdfLayer layer = ocProperties.GetLayers()[0];
                    NUnit.Framework.Assert.IsTrue(layer.GetPdfObject().IsFlushed());
                }
            }
        }
Example #22
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument  resultDoc = new PdfDocument(new PdfWriter(dest));
            MemoryStream tempFile  = new ByteArrayOutputStream();

            // The source pdf document's page size is expected to be huge: more than 14400 in width in height
            PdfDocument tempDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(tempFile));

            // Assume that there is a single XObject in the source document
            // and this single object is an image.
            PdfDictionary   pageDict      = tempDoc.GetFirstPage().GetPdfObject();
            PdfDictionary   pageResources = pageDict.GetAsDictionary(PdfName.Resources);
            PdfDictionary   pageXObjects  = pageResources.GetAsDictionary(PdfName.XObject);
            PdfName         imgRef        = pageXObjects.KeySet().First();
            PdfStream       imgStream     = pageXObjects.GetAsStream(imgRef);
            PdfImageXObject imgObject     = new PdfImageXObject(imgStream);
            Image           img           = new Image(imgObject);

            img.ScaleToFit(14400, 14400);
            img.SetFixedPosition(0, 0);

            tempDoc.AddNewPage(1, new PageSize(img.GetImageScaledWidth(), img.GetImageScaledHeight()));
            PdfPage page = tempDoc.GetFirstPage();

            new Canvas(page, page.GetPageSize())
            .Add(img)
            .Close();
            tempDoc.Close();

            PdfDocument docToCopy = new PdfDocument(new PdfReader(new MemoryStream(tempFile.ToArray())));

            docToCopy.CopyPagesTo(1, 1, resultDoc);

            docToCopy.Close();
            resultDoc.Close();
        }
        public virtual void CreatePdf(String dest1, String dest2)
        {
            PdfDocument destPdfDocument = new PdfDocument(new PdfWriter(dest1));
            //Smart mode
            PdfDocument destPdfDocumentSmartMode = new PdfDocument(new PdfWriter(dest2).SetSmartMode(true));

            using (StreamReader sr = File.OpenText(DATA))
            {
                String line;
                bool   headerLine = true;
                int    i          = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    if (headerLine)
                    {
                        headerLine = false;
                        continue;
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    PdfDocument           sourcePdfDocument = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                    //Read fields
                    PdfAcroForm     form      = PdfAcroForm.GetAcroForm(sourcePdfDocument, true);
                    StringTokenizer tokenizer = new StringTokenizer(line, ";");
                    IDictionary <String, PdfFormField> fields = form.GetFormFields();
                    //Fill out fields
                    PdfFormField toSet;
                    fields.TryGetValue("name", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("abbr", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("capital", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("city", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("population", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("surface", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("timezone1", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("timezone2", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("dst", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    //Flatten fields
                    form.FlattenFields();
                    sourcePdfDocument.Close();
                    sourcePdfDocument = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
                    //Copy pages
                    sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), destPdfDocument, null);
                    sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), destPdfDocumentSmartMode,
                                                  null);
                    sourcePdfDocument.Close();
                }
            }

            destPdfDocument.Close();
            destPdfDocumentSmartMode.Close();
        }
        public virtual void CreatePdf(String dest)
        {
            PdfDocument       pdfDocument = new PdfDocument(new PdfWriter(dest));
            PdfPageFormCopier formCopier  = new PdfPageFormCopier();

            using (StreamReader sr = File.OpenText(DATA))
            {
                String line;
                bool   headerLine = true;
                int    i          = 1;
                while ((line = sr.ReadLine()) != null)
                {
                    if (headerLine)
                    {
                        headerLine = false;
                        continue;
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    PdfDocument           sourcePdfDocument = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                    //Rename fields
                    i++;
                    PdfAcroForm form = PdfAcroForm.GetAcroForm(sourcePdfDocument, true);
                    form.RenameField("name", "name_" + i);
                    form.RenameField("abbr", "abbr_" + i);
                    form.RenameField("capital", "capital_" + i);
                    form.RenameField("city", "city_" + i);
                    form.RenameField("population", "population_" + i);
                    form.RenameField("surface", "surface_" + i);
                    form.RenameField("timezone1", "timezone1_" + i);
                    form.RenameField("timezone2", "timezone2_" + i);
                    form.RenameField("dst", "dst_" + i);
                    //Fill out fields
                    StringTokenizer tokenizer = new StringTokenizer(line, ";");
                    IDictionary <String, PdfFormField> fields = form.GetFormFields();
                    PdfFormField toSet;
                    fields.TryGetValue("name_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("abbr_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("capital_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("city_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("population_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("surface_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("timezone1_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("timezone2_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("dst_" + i, out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    sourcePdfDocument.Close();
                    sourcePdfDocument = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
                    //Copy pages
                    sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), pdfDocument, formCopier);
                    sourcePdfDocument.Close();
                }
            }

            pdfDocument.Close();
        }
Example #25
0
        public async Task <IActionResult> Convert()
        {
            StringValues clientParam;
            StringValues keyParam;
            StringValues orientationParam;
            StringValues pageSizeParam;
            var          hasClient      = Request.Query.TryGetValue("client", out clientParam);
            var          hasKey         = Request.Query.TryGetValue("key", out keyParam);
            var          hasOrientation = Request.Query.TryGetValue("orientation", out orientationParam);
            var          hasPageSize    = Request.Query.TryGetValue("pageSize", out pageSizeParam);
            var          client         = hasClient && clientParam.Count > 0 ? clientParam[0] : "";
            var          key            = hasKey && keyParam.Count > 0 ? keyParam[0] : "";
            var          orientation    = hasOrientation && orientationParam.Count > 0 ? orientationParam[0] : "portrait";
            var          pageSize       = hasPageSize && pageSizeParam.Count > 0 ? pageSizeParam[0] : "A4";

            if (!_clientKeys.ContainsKey(client) || _clientKeys[client] != key)
            {
                return(new NotFoundResult());
            }

            var formData = HttpContext.Request.Form;
            var files    = formData.Files;
            var docFile  = files.Where(f => f.FileName == "doc.html").FirstOrDefault();

            IActionResult response = null;

            if (docFile != null)
            {
                var tempFolder = $"{System.IO.Path.GetTempPath()}{Guid.NewGuid()}";
                Directory.CreateDirectory(tempFolder);

                foreach (var file in files)
                {
                    if (file.FileName != "doc.html")
                    {
                        await System.IO.File.WriteAllBytesAsync($"{tempFolder}/{file.FileName}", ReadAllBytes(file.OpenReadStream()));
                    }
                }

                try
                {
                    using (var htmlSource = docFile.OpenReadStream())
                        using (var pdfDest = new ByteArrayOutputStream())
                        {
                            var writer = new PdfWriter(pdfDest);
                            var pdfDoc = new PdfDocument(writer);
                            pdfDoc.SetTagged();

                            PageSize ps = PageSize.A4;

                            if (pageSize == "A3")
                            {
                                ps = PageSize.A3;
                            }

                            if (orientation == "landscape")
                            {
                                ps = ps.Rotate();
                            }

                            pdfDoc.SetDefaultPageSize(ps);

                            var converterProperties = new ConverterProperties();

                            var fp = new DefaultFontProvider();
                            fp.AddDirectory(tempFolder);
                            converterProperties.SetFontProvider(fp);

                            converterProperties.SetImmediateFlush(true);
                            converterProperties.SetBaseUri(new Uri(tempFolder).AbsoluteUri);
                            HtmlConverter.ConvertToPdf(htmlSource, pdfDoc, converterProperties);
                            var bytes = pdfDest.ToArray();
                            response = new FileContentResult(bytes, "application/pdf");
                        }
                }
                catch (Exception ex)
                {
                    response = StatusCode(500, new { error = ex.Message, stackTrace = ex.StackTrace });
                }

                Directory.Delete(tempFolder, true);
            }
            else
            {
                response = StatusCode((int)HttpStatusCode.BadRequest, new { error = "No doc file provided" });
            }

            return(response);
        }
Example #26
0
        internal static String GetStreamWithValue(PdfObject @object)
        {
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfOutputStream       stream = new PdfOutputStream(baos);

            stream.Write(@object);
            return("q\n" + "BT\n" + "/F1 12 Tf\n" + "36 787.96 Td\n" + iText.IO.Util.JavaUtil.GetStringForBytes(baos.ToArray
                                                                                                                    ()) + " Tj\n" + "ET\n" + "Q");
        }
Example #27
0
        public void GradeTest(ScannedTest test, string resultDestination)
        {
            if (test.TestGradeType == ScannedTest.GradeType.DifficultyAdjusted)
            {
                test.CalculateDifficulties();
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            var writer   = new PdfWriter(baos);
            var pdf      = new PdfDocument(writer);
            var document = new Document(pdf);
            int count    = 2 + test.AnswerKey.Count();

            float[] widths = new float[count + 3];
            widths[0]         = 8;
            widths[1]         = 2;
            widths[count]     = 3;
            widths[count + 1] = 3;
            widths[count + 2] = 3;
            for (int i = 2; i <= count - 1; i++)
            {
                widths[i] = 1;
            }

            Table scoreTable = new Table(widths);

            scoreTable.SetWidthPercent(100);
            scoreTable.AddCell(new Cell());
            scoreTable.AddCell(new Cell());
            for (int i = 1; i <= count - 2; i++)
            {
                scoreTable.AddCell(new Cell().Add(new Paragraph(i.ToString()).SetTextAlignment(TextAlignment.CENTER).SetFontSize(5)));
            }
            scoreTable.AddCell(new Cell().Add(new Paragraph("Correct")).SetFontSize(6).SetTextAlignment(TextAlignment.CENTER));
            scoreTable.AddCell(new Cell().Add(new Paragraph("Blank")).SetFontSize(6).SetTextAlignment(TextAlignment.CENTER));
            scoreTable.AddCell(new Cell().Add(new Paragraph("Score")).SetFontSize(6).SetTextAlignment(TextAlignment.CENTER));

            List <Table>  Tables = new List <Table>();
            List <double> Scores = new List <double>();

            //string[] id = File.ReadAllLines(studentListFile);
            scoreTable.AddCell(new Cell().Add(new Paragraph("Answer Key").SetTextAlignment(TextAlignment.CENTER).SetFontSize(8)));
            scoreTable.AddCell(new Cell().Add(new Paragraph(" ")));

            for (int i = 0; i < test.AnswerKey.Count; i++)
            {
                scoreTable.AddCell(new Cell().Add(new Paragraph(test.AnswerKey[i]).SetTextAlignment(TextAlignment.CENTER).SetFontSize(8)));
            }
            for (int i = 0; i <= 2; i++)
            {
                scoreTable.AddCell(new Cell().Add(new Paragraph(" ")));
            }

            for (int i = 0; i < test.Students.Count(); i++)
            {
                Table pTable = new Table(widths);
                pTable.SetWidthPercent(100);
                int    correct = 0;
                int    blank   = 0;
                double score   = 0;

                pTable.AddCell(new Cell().Add(new Paragraph(test.Students[i].Id).SetFontSize(8).SetTextAlignment(TextAlignment.CENTER)));
                pTable.AddCell(new Cell().Add(new Paragraph(" ")).SetFontSize(8));

                /* comment id search
                 * foreach (string s in id)
                 * {
                 *  if (s.Split(',')[0].Equals(data[i, 0]))
                 *  {
                 *      pTable.AddCell(new Cell().Add(new Paragraph(s.Split(',')[1])).SetFontSize(8));
                 *      pTable.AddCell(new Cell().Add(new Paragraph(s.Split(',')[0])).SetFontSize(8));
                 *      output = s.Split(',')[1];
                 *      output += " ";
                 *      output += s.Split(',')[0];
                 *  }
                 * }
                 */
                int question = 0;
                foreach (var answer in test.Students[i].Answers)
                {
                    if (answer.Equals(test.AnswerKey[question]))
                    {
                        pTable.AddCell(new Cell().Add(new Paragraph(answer.ToString())).SetTextAlignment(TextAlignment.CENTER).SetFontSize(8).SetFontColor(iText.Kernel.Colors.WebColors.GetRGBColor("Green")));
                        correct += 1;
                        switch (test.TestGradeType)
                        {
                        case ScannedTest.GradeType.AMC:
                            score += 6;
                            break;

                        case ScannedTest.GradeType.MuAlphaTheta:
                            score += 4;
                            break;

                        case ScannedTest.GradeType.Raw:
                            score += 1;
                            break;

                        case ScannedTest.GradeType.DifficultyAdjusted:
                            score += test.Difficulties[question];
                            break;
                        }
                    }
                    else if (answer.Equals("_"))
                    {
                        pTable.AddCell(new Cell().Add(new Paragraph(answer.ToString())).SetTextAlignment(TextAlignment.CENTER).SetFontSize(8).SetFontColor(iText.Kernel.Colors.WebColors.GetRGBColor("White")));
                        blank += 1;
                        switch (test.TestGradeType)
                        {
                        case ScannedTest.GradeType.AMC:
                            score += 1.5;
                            break;

                        case ScannedTest.GradeType.MuAlphaTheta:
                            score += 0;
                            break;

                        case ScannedTest.GradeType.Raw:
                            score += 0;
                            break;

                        case ScannedTest.GradeType.DifficultyAdjusted:
                            score += 0;
                            break;
                        }
                    }
                    else
                    {
                        switch (test.TestGradeType)
                        {
                        case ScannedTest.GradeType.AMC:
                            score += 0;
                            break;

                        case ScannedTest.GradeType.MuAlphaTheta:
                            score -= 1;
                            break;

                        case ScannedTest.GradeType.Raw:
                            score += 0;
                            break;

                        case ScannedTest.GradeType.DifficultyAdjusted:
                            score += 0;
                            break;
                        }
                        pTable.AddCell(new Cell().Add(new Paragraph(answer.ToString())).SetTextAlignment(TextAlignment.CENTER).SetFontSize(8).SetFontColor(iText.Kernel.Colors.WebColors.GetRGBColor("Red")));
                    }
                    question++;
                }

                pTable.AddCell(new Cell().Add(new Paragraph(correct.ToString()).SetFontSize(8).SetTextAlignment(TextAlignment.CENTER)));
                pTable.AddCell(new Cell().Add(new Paragraph(blank.ToString()).SetTextAlignment(TextAlignment.CENTER).SetFontSize(8)));
                string formatString = "{0:#0}";
                switch (test.TestGradeType)
                {
                case ScannedTest.GradeType.AMC:
                    formatString = "{0:##0.0}";
                    break;

                case ScannedTest.GradeType.DifficultyAdjusted:
                    formatString = "{0:#0.00}";
                    break;
                }
                pTable.AddCell(new Cell().Add(new Paragraph(String.Format(formatString, score)).SetTextAlignment(TextAlignment.CENTER).SetFontSize(8)));
                Tables.Add(pTable);
                Scores.Add(score);
            }

            document.Add(scoreTable);
            while (Scores.Count() > 0)
            {
                int loc = Scores.IndexOf(Scores.Max());
                document.Add(Tables[loc]);
                Tables.RemoveAt(loc);
                Scores.RemoveAt(loc);
            }
            document.Close();
            File.WriteAllBytes(resultDestination, baos.ToArray());
            //Console.ReadLine();
        }
        public virtual void CleanUpRedactAnnotationsWithAdditionalLocationSendsCoreAndCleanUpEventTest()
        {
            ByteArrayOutputStream baos     = new ByteArrayOutputStream();
            PdfDocument           document = new PdfDocument(new PdfReader(INPUT_PATH + "absentICentry.pdf"), new PdfWriter(baos
                                                                                                                            ));
            String oldProducer = document.GetDocumentInfo().GetProducer();
            IList <iText.PdfCleanup.PdfCleanUpLocation> cleanUpLocations = new List <iText.PdfCleanup.PdfCleanUpLocation
                                                                                     >();

            iText.PdfCleanup.PdfCleanUpLocation lineLoc = new iText.PdfCleanup.PdfCleanUpLocation(1, new Rectangle(100
                                                                                                                   , 560, 200, 30), ColorConstants.GREEN);
            cleanUpLocations.Add(lineLoc);
            PdfCleaner.CleanUpRedactAnnotations(document, cleanUpLocations);
            document.Close();
            IList <ConfirmEvent> events = handler.GetEvents();

            NUnit.Framework.Assert.AreEqual(2, events.Count);
            NUnit.Framework.Assert.AreEqual(ITextCoreProductEvent.PROCESS_PDF, events[0].GetEvent().GetEventType());
            NUnit.Framework.Assert.AreEqual(PdfSweepProductEvent.CLEANUP_PDF, events[1].GetEvent().GetEventType());
            using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())))) {
                String expectedProdLine = CreateExpectedProducerLine(new ConfirmedEventWrapper[] { GetCoreEvent(), GetCleanUpEvent
                                                                                                       () }, oldProducer);
                NUnit.Framework.Assert.AreEqual(expectedProdLine, pdfDocument.GetDocumentInfo().GetProducer());
            }
        }
        public virtual void AutoSweepTentativeCleanUpSendsCoreEventTest()
        {
            ByteArrayOutputStream    baos     = new ByteArrayOutputStream();
            PdfDocument              document = new PdfDocument(new PdfReader(INPUT_PATH + "fontCleanup.pdf"), new PdfWriter(baos));
            CompositeCleanupStrategy strategy = new CompositeCleanupStrategy();

            strategy.Add(new RegexBasedCleanupStrategy("leonard"));
            PdfAutoSweepTools autoSweep = new PdfAutoSweepTools(strategy);

            autoSweep.TentativeCleanUp(document);
            String oldProducer = document.GetDocumentInfo().GetProducer();

            document.Close();
            IList <ConfirmEvent> events = handler.GetEvents();

            NUnit.Framework.Assert.AreEqual(1, events.Count);
            NUnit.Framework.Assert.AreEqual(ITextCoreProductEvent.PROCESS_PDF, events[0].GetEvent().GetEventType());
            using (PdfDocument pdfDocument = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())))) {
                String expectedProdLine = CreateExpectedProducerLine(new ConfirmedEventWrapper[] { GetCoreEvent() }, oldProducer
                                                                     );
                NUnit.Framework.Assert.AreEqual(expectedProdLine, pdfDocument.GetDocumentInfo().GetProducer());
            }
        }