Ejemplo n.º 1
0
        virtual public void FileSpecCheckTest3()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest3.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B);

            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            byte[] somePdf = new byte[25];
            writer.AddFileAttachment("some pdf file", somePdf, "foo.pdf", "foo.pdf", PdfAWriter.MimeTypePdf,
                                     AFRelationshipValue.Data);

            document.Close();
        }
Ejemplo n.º 2
0
        public static void CreatePDFA3Invoice(string pdfFilePath, string embbedFilePath, string outputPath, string colorProfilePath)
        {
            PdfReader    reader = new PdfReader(pdfFilePath);
            MemoryStream stream = new MemoryStream();
            Document     doc    = new Document();
            PdfAWriter   writer = CreatePDFAInstance(doc, reader, stream);


            // Create Output Intents
            ICC_Profile icc = ICC_Profile.GetInstance(File.ReadAllBytes(colorProfilePath));

            writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfArray array = new PdfArray();

            writer.ExtraCatalog.Put(new PdfName("AF"), array);

            PdfFileSpecification contentSpec = EmbeddedAttachment(embbedFilePath, Path.GetFileName(embbedFilePath),
                                                                  "text/xml", new PdfName("Alternative"), writer, "XML Data");

            array.Add(contentSpec.Reference);


            //string stringExchangeXMP = File.ReadAllText(@"..\..\Resources/EDocument_PDFAExtensionSchema.xml");
            //byte[] exchangeXMP = Encoding.ASCII.GetBytes(stringExchangeXMP);
            //writer.XmpMetadata = exchangeXMP;
            //XmpWriter xmp = new XmpWriter(stream, reader.Info);
            //writer.XmpMetadata = stream.ToArray();

            doc.Close();
            reader.Close();
            File.WriteAllBytes(outputPath, stream.ToArray());
        }
Ejemplo n.º 3
0
        public virtual void TestImportedPage5()
        {
            String f1       = RESOURCES + "copy/pdfa-3a.pdf";
            String f2       = RESOURCES + "copy/pdfa-3u.pdf";
            String testName = "testImportedPage5.pdf";

            Stream   outputPdfStream = new FileStream(outputDir + testName, FileMode.Create);
            Document document        = new Document();
            PdfACopy copy            = new PdfACopy(document, outputPdfStream, PdfAConformanceLevel.PDF_A_3U);

            copy.CreateXmpMetadata();
            document.Open();

            foreach (String f in new String[] { f1, f2 })
            {
                PdfReader reader = new PdfReader(f);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    copy.AddPage(copy.GetImportedPage(reader, i));
                }
            }

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read,
                                                        FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            copy.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            copy.Close();
        }
Ejemplo n.º 4
0
        public virtual void TestMergeFields1()
        {
            String f1       = RESOURCES + "copy/pdfa-1a.pdf";
            String f2       = RESOURCES + "copy/pdfa-1a-2.pdf";
            String testName = "testMergeFields1.pdf";

            FileStream outputPdfStream = new FileStream(outputDir + testName, FileMode.Create);
            Document   document        = new Document();
            PdfACopy   copy            = new PdfACopy(document, outputPdfStream, PdfAConformanceLevel.PDF_A_1A);

            copy.SetMergeFields();
            copy.CreateXmpMetadata();
            copy.SetTagged();
            document.Open();
            document.AddLanguage("en-US");
            foreach (String f in new String[] { f1, f2 })
            {
                PdfReader reader = new PdfReader(f);
                copy.AddDocument(reader);
            }

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read,
                                                        FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            copy.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            copy.Close();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Rubber stamps an image based PDF as a PDF/A-1B pdf.
        /// </summary>
        /// <param name="oldFile">The original pdf file.</param>
        /// <param name="newFile">The new pdf file.</param>
        public void ConvertPDF(FileInfo oldFile, FileInfo newFile)
        {
            using (FileStream fs = new FileStream(newFile.FullName, FileMode.Create, FileAccess.Write))
                using (PdfReader pdf = new PdfReader(oldFile.FullName))
                    using (iTextSharp.text.Document doc = new iTextSharp.text.Document(pdf.GetPageSizeWithRotation(1)))
                        using (PdfAWriter writer = PdfAWriter.GetInstance(doc, fs, PdfAConformanceLevel.PDF_A_1B))
                        {
                            doc.Open();
                            ICC_Profile icc = ICC_Profile.GetInstance(Environment.GetEnvironmentVariable("SystemRoot") + @"\System32\spool\drivers\color\sRGB Color Space Profile.icm");
                            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
                            PdfContentByte contentByte = writer.DirectContent;

                            for (int i = 1; i <= pdf.NumberOfPages; i++)
                            {
                                doc.SetPageSize(pdf.GetPageSizeWithRotation(i));
                                doc.NewPage();
                                PdfImportedPage page = writer.GetImportedPage(pdf, i);
                                contentByte.AddTemplate(page, 0, 0);
                            }

                            writer.CreateXmpMetadata();
                            doc.Close();
                        }

            OnPdfConverted(oldFile);
        }
Ejemplo n.º 6
0
        virtual public void FileSpecCheckTest2()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest2.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B);

            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            MemoryStream txt  = new MemoryStream();
            StreamWriter outp = new StreamWriter(txt);

            outp.Write("<foo><foo2>Hello world</foo2></foo>");
            outp.Close();

            PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(writer, null, "foo.xml", txt.ToArray());

            fs.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Unspecified);

            writer.AddFileAttachment(fs);

            document.Close();
        }
Ejemplo n.º 7
0
        virtual public void FileSpecCheckTest6()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest2.pdf", FileMode.Create),
                                                         PdfAConformanceLevel.PDF_A_3B);

            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open,
                                                        FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfDictionary _params = new PdfDictionary();

            _params.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(
                writer, RESOURCES + "foo.xml", "foo.xml", null, false, "text/xml", _params);

            fileSpec.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Data);

            writer.AddFileAttachment(fileSpec);

            document.Close();
        }
Ejemplo n.º 8
0
        virtual public void CreatePdfAutomaticTest()
        {
            String fileName = "xmp_metadata_automatic.pdf";
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create),
                                                      PdfAConformanceLevel.PDF_A_1B);

            document.AddTitle("Hello World example");
            document.AddSubject("This example shows how to add metadata & XMP");
            document.AddKeywords("Metadata, iText, step 3");
            document.AddCreator("My program using 'iText'");
            document.AddAuthor("Bruno Lowagie & Paulo Soares");
            writer.CreateXmpMetadata();
            // step 3
            document.Open();
            Font font = FontFactory.GetFont("../../resources/text/pdfa/FreeMonoBold.ttf", BaseFont.WINANSI,
                                            BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream iccStream = new FileStream("../../resources/text/pdfa/sRGB Color Space Profile.icm",
                                                  FileMode.Open);
            ICC_Profile icc = ICC_Profile.GetInstance(iccStream);

            iccStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            // step 5
            document.Close();
            CompareResults(fileName, fileName);
        }
Ejemplo n.º 9
0
        // ---------------------------------------------------------------------------

        /**
         * Creates a PDF document.
         */
        public byte[] CreatePdfA()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // step 1
                using (Document document = new Document())
                {
                    // step 2
                    PdfAWriter writer = PdfAWriter.GetInstance(document, ms, PdfAConformanceLevel.PDF_A_1B);
                    //PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    //writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_4);
                    //writer.PDFXConformance = PdfWriter.PDFA1B;
                    writer.CreateXmpMetadata();
                    // step 3
                    document.Open();
                    // step 4
                    Font font = FontFactory.GetFont(FONT, BaseFont.CP1252, BaseFont.EMBEDDED);
                    document.Add(new Paragraph("Hello World", font));
                    using (FileStream fs2 = new FileStream(
                               PROFILE, FileMode.Open, FileAccess.Read, FileShare.Read
                               ))
                    {
                        ICC_Profile icc = ICC_Profile.GetInstance(fs2);
                        writer.SetOutputIntents(
                            "Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc
                            );
                    }
                }
                return(ms.ToArray());
            }
        }
Ejemplo n.º 10
0
        public void TestNotoFont()
        {
            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, new MemoryStream(), PdfAConformanceLevel.PDF_A_1B);

            writer.CreateXmpMetadata();

            document.Open();
            FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();
            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            String   fontPath = RESOURCES + "NotoSansCJKjp-Bold.otf";
            BaseFont bf       = BaseFont.CreateFont(fontPath, "Identity-H", true);
            Font     font     = new Font(bf, 14);

            String[] lines = new String[] { "Noto test", "in japanese:", "\u713C" };

            foreach (String line in lines)
            {
                document.Add(new Paragraph(line, font));
            }

            document.Close();
        }
Ejemplo n.º 11
0
        virtual public void TestPdfAStamper1()
        {
            string     filename = OUT + "TestPdfAStamper1.pdf";
            FileStream fos      = new FileStream(filename, FileMode.Create);

            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_1B);

            writer.CreateXmpMetadata();

            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            document.Close();

            PdfReader   reader            = new PdfReader(filename);
            FileStream  stamperFileStream = new FileStream(OUT + "TestPdfAStamper1_.pdf", FileMode.Create);
            PdfAStamper stamper           = new PdfAStamper(reader, stamperFileStream, PdfAConformanceLevel.PDF_A_1B);

            stamper.Close();
            stamperFileStream.Close();
            reader.Close();
        }
Ejemplo n.º 12
0
        virtual public void TestCreatePdfA_1()
        {
            Document   document;
            PdfAWriter writer;

            try
            {
                string     filename = OUT + "TestCreatePdfA_1.pdf";
                FileStream fos      = new FileStream(filename, FileMode.Create);

                document = new Document();

                writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_1B);
                writer.CreateXmpMetadata();

                document.Open();

                Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
                document.Add(new Paragraph("Hello World", font));

                FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
                ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
                iccProfileFileStream.Close();

                writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
                document.Close();
            }
            catch (PdfAConformanceException e)
            {
                Assert.Fail("PdfAConformance exception should not be thrown: " + e.Message);
            }
        }
Ejemplo n.º 13
0
        public virtual void TestCreatePdfA_1()
        {
            String f1       = RESOURCES + "copy\\pdfa-1a.pdf";
            String testName = "testCreatePdfA_1.pdf";

            FileStream outputPdfStream = new FileStream(outputDir + testName, FileMode.Create);
            Document   document        = new Document();
            PdfACopy   copy            = new PdfACopy(document, outputPdfStream, PdfAConformanceLevel.PDF_A_1B);

            copy.CreateXmpMetadata();
            document.Open();
            document.AddLanguage("en-US");
            PdfReader reader = new PdfReader(f1);

            PdfImportedPage page = copy.GetImportedPage(reader, 1);

            PdfCopy.PageStamp stamp = copy.CreatePageStamp(page);
            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 24);

            ColumnText.ShowTextAligned(stamp.GetUnderContent(), Element.ALIGN_CENTER, new Phrase("Hello world!", font), 100, 500, 0);
            stamp.AlterContents();
            copy.AddPage(page);

            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read,
                                                        FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            copy.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            copy.Close();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Must use this after calling document.Open()
        /// </summary>
        /// <param name="writer"></param>
        /// <returns></returns>
        public static PdfWriter RegisterFonts(this PdfWriter writer)
        {
            FontFactory.RegisterDirectories();
            var icc = ICC_Profile.GetInstance((byte[])Properties.Resources.ResourceManager.GetObject("icc_profile"));

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            return(writer);
        }
Ejemplo n.º 15
0
        private void GenerateEAttachmentDocument(PdfAWriter writer, XmpWriter xmpWriter, EAttactment attachment)
        {
            // Use default intent if output intent of this instance was not set
            if (attachment.outputIntents == null)
            {
                //byte[] iccProfile = File.ReadAllBytes("/Resources/sRGB Color Space Profile.icm");
                byte[]      iccProfile = Properties.Resources.sRGB_Color_Space_Profile;
                ICC_Profile icc        = ICC_Profile.GetInstance(iccProfile);
                writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            }
            else
            {
                OutputIntents outputIntents       = attachment.outputIntents;
                byte[]        iccProfileByteArray = File.ReadAllBytes(outputIntents.colorProfilePath);
                ICC_Profile   icc = ICC_Profile.GetInstance(iccProfileByteArray);
                writer.SetOutputIntents(outputIntents.outputConditionIdentifier, outputIntents.outputCondition, outputIntents.registryName, outputIntents.info, icc);
            }

            //============= Create Exchange ECertificate =================
            // 1 add ContentInformation.xml to document
            PdfArray attachmentArray = new PdfArray();

            writer.ExtraCatalog.Put(new PdfName("AF"), attachmentArray);
            PdfFileSpecification contentSpec = this.EmbeddedAttachment(attachment.contentInformationXMLPath, attachment.attachmentName,
                                                                       attachment.attachmentMIME, new PdfName(attachment.attachmentType), writer, attachment.attachmentDescription);

            attachmentArray.Add(contentSpec.Reference);

            foreach (var item in attachment.fileAttachments)
            {
                contentSpec = this.EmbeddedAttachment(item.attachmentPath, item.attachmentName,
                                                      item.attachmentMIME, new PdfName(item.attachmentType), writer, item.attachmentDescription);
                attachmentArray.Add(contentSpec.Reference);
            }

            // 2 add Electronic Document XMP Metadata
            ElectronicDocumentSchema ed = ElectronicDocumentSchema.generateED(attachment.attachmentName, attachment.documentVersion, attachment.documentID, attachment.documentOID);

            xmpWriter.AddRdfDescription(ed);

            string pdfaSchema = Properties.Resources.EDocument_PDFAExtensionSchema;

            // convert string to stream
            byte[] byteArray = Encoding.UTF8.GetBytes(pdfaSchema);


            //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
            MemoryStream stream          = new MemoryStream(byteArray);
            IXmpMeta     edPDFAextension = XmpMetaFactory.Parse(stream);
            IXmpMeta     originalXMP     = xmpWriter.XmpMeta;

            XmpUtils.AppendProperties(edPDFAextension, originalXMP, true, true);
        }
Ejemplo n.º 16
0
        private static void SetPdfAConformance(PdfReader reader, Document doc, MemoryStream ms)
        {
            // Create PdfAWriter with PdfAConformanceLevel.PDF_A_3B option if you
            // want to get a PDF/A-3b compliant document.
            PdfAWriter writer = PdfAWriter.GetInstance(doc, ms, _pdfaConformanceLevel);

            // Create XMP metadata. It's a PDF/A requirement.
            writer.CreateXmpMetadata();

            doc.Open();

            // Set output intent. PDF/A requirement.
            ICC_Profile icc = ICC_Profile
                              .GetInstance(new FileStream(@"resources/sRGB Color Space Profile.icm", FileMode.Open));

            writer.SetOutputIntents("Custom", "", "http://www.color.org",
                                    "sRGB IEC61966-2.1", icc);

            // Creating PDF/A-3 compliant attachment.
            PdfDictionary parameters = new PdfDictionary();

            parameters.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(
                writer, _inputFilePath,
                "test.pdf", null, "application/pdf", parameters, 0);

            fileSpec.Put(new PdfName("AFRelationship"), new PdfName("Data"));
            writer.AddFileAttachment("test.pdf", fileSpec);
            PdfArray array = new PdfArray {
                fileSpec.Reference
            };

            writer.ExtraCatalog.Put(new PdfName("AF"), array);

            doc.AddDocListener(writer);
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                doc.SetPageSize(reader.GetPageSize(i));
                doc.NewPage();
                PdfContentByte  cb       = writer.DirectContent;
                PdfImportedPage page     = writer.GetImportedPage(reader, i);
                int             rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
                }
            }
        }
Ejemplo n.º 17
0
        public void BarcodesTest1()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new
                                                         FileStream(OUT + "barcodesTest1.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3A);

            writer.SetTagged();
            document.Open();
            writer.ViewerPreferences = PdfWriter.DisplayDocTitle;
            document.AddTitle("Some title");
            document.AddLanguage("en-us");
            writer.CreateXmpMetadata();

            document.NewPage();

            // Set output intent. PDF/A requirement.
            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open,
                                                        FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();
            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            // All fonts shall be embedded. PDF/A requirement.
            Font normal9 = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 9);
            Font normal8 = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 8);

            BaseColor color = new BaseColor(111, 211, 11);

            normal8.Color = color;

            PdfContentByte cb = writer.DirectContent;

            String  code    = "119716-500023718";
            Barcode barcode = new Barcode39();

            barcode.Code          = code;
            barcode.StartStopText = false;
            barcode.Font          = normal9.BaseFont;
            barcode.Extended      = true;

            Image image = barcode.CreateImageWithBarcode(cb, color, color);

            image.Alt = "Bla Bla";
            document.Add(image);

            document.Close();
        }
Ejemplo n.º 18
0
        //static void Main(string[] args)
        //{
        //    PDFA3Invoice core = new PDFA3Invoice();
        //    String pdfFilePath = "in/test.pdf";
        //    String xmlFilePath = "in/ContentInformation.xml";
        //    String xmlFileName = "content.xml";
        //    String xmlVersion = "1.0";
        //    String documentID = "TIV0000012";
        //    String documentOID = "";
        //    String outputPath = "out/test.pdf";

        //    core.CreatePDFA3Invoice(pdfFilePath, xmlFilePath, xmlFileName, xmlVersion,
        //        documentID, documentOID, outputPath);

        //    Console.ReadLine();
        //}

        public void CreatePDFA3Invoice(string pdfFilePath, string xmlFilePath, string xmlFileName,
                                       string xmlVersion, string documentID, string documentOID, string outputPath, string documentType)
        {
            // =========== Create PDF/A-3U Document =================
            // Create PDF/A-3U writer instance from existing document
            PdfReader    reader       = new PdfReader(pdfFilePath);
            MemoryStream stream       = new MemoryStream();
            Document     pdfAdocument = new Document();
            PdfAWriter   writer       = this.CreatePDFAInstance(pdfAdocument, reader, stream);

            // Create Output Intents
            ICC_Profile icc = ICC_Profile.GetInstance("Resources/sRGB Color Space Profile.icm");

            writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfArray array = new PdfArray();

            writer.ExtraCatalog.Put(new PdfName("AF"), array);

            //============= Create Exchange Invoice =================
            // 1 add xml to document
            PdfFileSpecification contentSpec = this.EmbeddedAttachment(xmlFilePath, xmlFileName,
                                                                       "text/xml", new PdfName("Alternative"), writer, "Tax Invoice XML Data");

            array.Add(contentSpec.Reference);

            //byte[] exchangeXMP = File.ReadAllBytes("Resources/EDocument_PDFAExtensionSchema.xml");
            string stringExchangeXMP = File.ReadAllText("Resources/EDocument_PDFAExtensionSchema.xml");

            byte[] exchangeXMP = Encoding.ASCII.GetBytes(stringExchangeXMP.Replace("@DocumentType", documentType));
            writer.XmpMetadata = exchangeXMP;

            //// 2 add Electronic Document XMP Metadata
            //ElectronicDocument ed = ElectronicDocument.generateED(xmlFileName, xmlVersion, documentID, documentOID);
            //XmpWriter xmpWriter = writer.XmpWriter;
            //xmpWriter.AddRdfDescription(ed);

            //IXmpMeta edPDFAextension = XmpMetaFactory.Parse(new FileStream("Resources/EDocument_PDFAExtensionSchema.xml", FileMode.Open));
            //IXmpMeta originalXMP = xmpWriter.XmpMeta;

            //XmpUtils.AppendProperties(edPDFAextension, originalXMP, true, true);

            pdfAdocument.Close();
            reader.Close();

            File.WriteAllBytes(outputPath, stream.ToArray());
        }
Ejemplo n.º 19
0
 private void generatePDFA3Document(PdfAWriter writer, OutputIntents outputIntents)
 {
     // Use default intent if output intent of this instance was not set
     if (outputIntents == null)
     {
         //byte[] iccProfile = File.ReadAllBytes("/Resources/sRGB Color Space Profile.icm");
         byte[]      iccProfileByteArray = Properties.Resources.sRGB_Color_Space_Profile;
         ICC_Profile icc = ICC_Profile.GetInstance(iccProfileByteArray);
         writer.SetOutputIntents("sRGB IEC61966-2.1", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
     }
     else
     {
         byte[]      iccProfileByteArray = File.ReadAllBytes(outputIntents.colorProfilePath);
         ICC_Profile icc = ICC_Profile.GetInstance(iccProfileByteArray);
         writer.SetOutputIntents(outputIntents.outputConditionIdentifier, outputIntents.outputCondition, outputIntents.registryName, outputIntents.info, icc);
     }
 }
Ejemplo n.º 20
0
        public void TestPdfAStamper2()
        {
            string     filename = OUT + "TestPdfAStamper2.pdf";
            FileStream fos      = new FileStream(filename, FileMode.Create);

            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_2B);

            writer.CreateXmpMetadata();

            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream  iccProfileFileStream = new FileStream(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            document.Close();

            PdfReader reader          = new PdfReader(filename);
            bool      exceptionThrown = false;

            try
            {
                FileStream  stamperFileStream = new FileStream(OUT + "TestPdfAStamper2_.pdf", FileMode.Create);
                PdfAStamper stamper           = new PdfAStamper(reader, stamperFileStream, PdfAConformanceLevel.PDF_A_1B);
                stamper.Close();
                stamperFileStream.Close();
            }
            catch (PdfAConformanceException)
            {
                exceptionThrown = true;
            }
            reader.Close();
            if (!exceptionThrown)
            {
                Assert.Fail("PdfAConformance exception should be thrown");
            }
        }
Ejemplo n.º 21
0
        virtual public void DeprecatedLogicTest()
        {
            String fileName = "xmp_metadata_deprecated.pdf";
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create),
                                                      PdfAConformanceLevel.PDF_A_2B);
            MemoryStream os      = new MemoryStream();
            XmpWriter    xmp     = new PdfAXmpWriter(os, PdfAConformanceLevel.PDF_A_2B, writer);
            XmpSchema    dc      = new DublinCoreSchema();
            XmpArray     subject = new XmpArray(XmpArray.UNORDERED);

            subject.Add("Hello World");
            subject.Add("XMP & Metadata");
            subject.Add("Metadata");
            dc.SetProperty(DublinCoreSchema.SUBJECT, subject);
            xmp.AddRdfDescription(dc.Xmlns, dc.ToString());
            PdfSchema pdf = new PdfSchema();

            pdf.AddKeywords("Hello World, XMP & Metadata, Metadata");
            pdf.AddVersion("1.4");
            xmp.AddRdfDescription(pdf);
            xmp.Close();
            writer.XmpMetadata = os.ToArray();
            // step 3
            document.Open();
            document.AddLanguage("en_US");
            // step 4
            Font font = FontFactory.GetFont("../../resources/text/pdfa/FreeMonoBold.ttf", BaseFont.WINANSI,
                                            BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream iccStream = new FileStream("../../resources/text/pdfa/sRGB Color Space Profile.icm",
                                                  FileMode.Open);
            ICC_Profile icc = ICC_Profile.GetInstance(iccStream);

            iccStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            // step 5
            document.Close();
            CompareResults("xmp_metadata_deprecated.pdf", fileName);
        }
Ejemplo n.º 22
0
        virtual public void FileSpecCheckTest5()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "fileSpecCheckTest5.pdf", FileMode.Create), PdfAConformanceLevel.PDF_A_3B);

            writer.CreateXmpMetadata();
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));

            FileStream  iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();

            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            MemoryStream txt  = new MemoryStream();
            StreamWriter outp = new StreamWriter(txt);

            outp.Write("<foo><foo2>Hello world</foo2></foo>");
            outp.Close();

            bool exceptionThrown = false;

            try {
                PdfFileSpecification fs
                    = PdfFileSpecification.FileEmbedded(writer,
                                                        null, "foo.xml", txt.ToArray());
                writer.AddFileAttachment(fs);
            }
            catch (PdfAConformanceException e) {
                if (e.GetObject() != null && e.Message.Equals("The file specification dictionary for an embedded file shall contain correct AFRelationship key."))
                {
                    exceptionThrown = true;
                }
            }
            if (!exceptionThrown)
            {
                Assert.Fail("PdfAConformanceException with correct message should be thrown.");
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Sets PDF/A Conformance ColorProfile.
        /// </summary>
        public void SetColorProfile()
        {
            if (PageSetup.ConformanceLevel == PdfXConformance.PDFXNONE)
            {
                return;
            }

            var pdfDictionary = new PdfDictionary(PdfName.OUTPUTINTENT);

            pdfDictionary.Put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1"));
            pdfDictionary.Put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
            pdfDictionary.Put(PdfName.S, PdfName.GTS_PDFA1);

            var profileStream = StreamHelper.GetResourceByName("PdfRpt.Core.Helper.srgb.profile");
            var pdfICCBased   = new PdfICCBased(ICC_Profile.GetInstance(profileStream));

            pdfICCBased.Remove(PdfName.ALTERNATE);
            pdfDictionary.Put(PdfName.DESTOUTPUTPROFILE, PdfWriter.AddToBody(pdfICCBased).IndirectReference);

            PdfWriter.ExtraCatalog.Put(PdfName.OUTPUTINTENTS, new PdfArray(pdfDictionary));
        }
Ejemplo n.º 24
0
                public void CreatePdfA(PdfAConformanceLevel level)
                {
                    Document doc = new Document();

                    MemoryStream stream = new MemoryStream();
                    PdfAWriter   writer = PdfAWriter.GetInstance(doc, stream, level);

                    doc.Open();

                    ICC_Profile icc = ICC_Profile.GetInstance(File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read));

                    writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
                    writer.CreateXmpMetadata();

                    Font font = FontFactory.GetFont("FreeSans", BaseFont.IDENTITY_H, true, 12);

                    doc.Add(new Phrase("Hello, " + level + " world!", font));
                    doc.Add(new Phrase(Guid.NewGuid().ToString(), font));

                    doc.Close();
                }
Ejemplo n.º 25
0
        virtual public void CreatePdfTest()
        {
            String fileName = "xmp_metadata.pdf";
            // step 1
            Document document = new Document();
            // step 2
            PdfWriter writer = PdfAWriter.GetInstance(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create),
                                                      PdfAConformanceLevel.PDF_A_2B);

            writer.SetTagged();
            writer.CreateXmpMetadata();
            XmpWriter xmp = writer.XmpWriter;

            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Hello World");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "XMP & Metadata");
            DublinCoreProperties.AddSubject(xmp.XmpMeta, "Metadata");

            PdfProperties.SetKeywords(xmp.XmpMeta, "Hello World, XMP & Metadata, Metadata");
            PdfProperties.SetVersion(xmp.XmpMeta, "1.4");

            // step 3
            document.Open();
            document.AddLanguage("en_US");

            // step 4
            Font font = FontFactory.GetFont("../../resources/text/pdfa/FreeMonoBold.ttf", BaseFont.WINANSI,
                                            BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));
            FileStream iccStream = new FileStream("../../resources/text/pdfa/sRGB Color Space Profile.icm",
                                                  FileMode.Open);
            ICC_Profile icc = ICC_Profile.GetInstance(iccStream);

            iccStream.Close();
            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            // step 5
            document.Close();

            CompareResults(fileName, fileName);
        }
Ejemplo n.º 26
0
        public void ZugferdInvoiceTest()
        {
            Document   document = new Document();
            PdfAWriter writer   = PdfAWriter.GetInstance(document, new FileStream(OUT + "zugferdInvoiceTest.pdf", FileMode.Create),
                                                         PdfAConformanceLevel.ZUGFeRD);

            writer.CreateXmpMetadata();
            writer.XmpWriter.SetProperty(PdfAXmpWriter.zugferdSchemaNS, PdfAXmpWriter.zugferdDocumentFileName, "invoice.xml");
            document.Open();

            Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, 12);

            document.Add(new Paragraph("Hello World", font));
            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open,
                                                        FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);

            iccProfileFileStream.Close();
            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            PdfDictionary parameters = new PdfDictionary();

            parameters.Put(PdfName.MODDATE, new PdfDate());
            PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(
                writer, RESOURCES + "invoice.xml",
                "invoice.xml", null, "application/xml", parameters, 0);

            fileSpec.Put(PdfName.AFRELATIONSHIP, AFRelationshipValue.Alternative);
            writer.AddFileAttachment("invoice.xml", fileSpec);
            PdfArray array = new PdfArray();

            array.Add(fileSpec.Reference);
            writer.ExtraCatalog.Put(new PdfName("AF"), array);

            document.Close();
        }
Ejemplo n.º 27
0
        /** Reads a page from a TIFF image.
         * @param s the file source
         * @param page the page to get. The first page is 1
         * @param direct for single strip, CCITT images, generate the image
         * by direct byte copying. It's faster but may not work
         * every time
         * @return the <CODE>Image</CODE>
         */
        public static Image GetTiffImage(RandomAccessFileOrArray s, int page, bool direct)
        {
            if (page < 1)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("the.page.number.must.be.gt.eq.1"));
            }
            TIFFDirectory dir = new TIFFDirectory(s, page - 1);

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("tiles.are.not.supported"));
            }
            int compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_CCITTRLEW:
            case TIFFConstants.COMPRESSION_CCITTRLE:
            case TIFFConstants.COMPRESSION_CCITTFAX3:
            case TIFFConstants.COMPRESSION_CCITTFAX4:
                break;

            default:
                return(GetTiffImageColor(dir, s));
            }
            float rotation = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
            {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            Image img            = null;
            long  tiffT4Options  = 0;
            long  tiffT6Options  = 0;
            int   fillOrder      = 1;
            int   h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int   w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int   dpiX           = 0;
            int   dpiY           = 0;
            float XYRatio        = 0;
            int   resolutionUnit = TIFFConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            }
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            if (resolutionUnit == TIFFConstants.RESUNIT_NONE)
            {
                if (dpiY != 0)
                {
                    XYRatio = (float)dpiX / (float)dpiY;
                }
                dpiX = 0;
                dpiY = 0;
            }
            int rowsStrip = h;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP))
            {
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            }
            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)   // some TIFF producers are really lousy, so...
            {
                size = new long[] { s.Length - (int)offset[0] };
            }
            bool      reverse        = false;
            TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int paramsn = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC))
            {
                long photo = dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);
                if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK)
                {
                    paramsn |= Image.CCITT_BLACKIS1;
                }
            }
            int imagecomp = 0;

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_CCITTRLEW:
            case TIFFConstants.COMPRESSION_CCITTRLE:
                imagecomp = Image.CCITTG3_1D;
                paramsn  |= Image.CCITT_ENCODEDBYTEALIGN | Image.CCITT_ENDOFBLOCK;
                break;

            case TIFFConstants.COMPRESSION_CCITTFAX3:
                imagecomp = Image.CCITTG3_1D;
                paramsn  |= Image.CCITT_ENDOFLINE | Image.CCITT_ENDOFBLOCK;
                TIFFField t4OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP3OPTIONS);
                if (t4OptionsField != null)
                {
                    tiffT4Options = t4OptionsField.GetAsLong(0);
                    if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0)
                    {
                        imagecomp = Image.CCITTG3_2D;
                    }
                    if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0)
                    {
                        paramsn |= Image.CCITT_ENCODEDBYTEALIGN;
                    }
                }
                break;

            case TIFFConstants.COMPRESSION_CCITTFAX4:
                imagecomp = Image.CCITTG4;
                TIFFField t6OptionsField = dir.GetField(TIFFConstants.TIFFTAG_GROUP4OPTIONS);
                if (t6OptionsField != null)
                {
                    tiffT6Options = t6OptionsField.GetAsLong(0);
                }
                break;
            }
            if (direct && rowsStrip == h)   //single strip, direct
            {
                byte[] im = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(im);
                img          = Image.GetInstance(w, h, false, imagecomp, paramsn, im);
                img.Inverted = true;
            }
            else
            {
                int            rowsLeft = h;
                CCITTG4Encoder g4       = new CCITTG4Encoder(w);
                for (int k = 0; k < offset.Length; ++k)
                {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int            height  = Math.Min(rowsStrip, rowsLeft);
                    TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height);
                    byte[]         outBuf  = new byte[(w + 7) / 8 * height];
                    switch (compression)
                    {
                    case TIFFConstants.COMPRESSION_CCITTRLEW:
                    case TIFFConstants.COMPRESSION_CCITTRLE:
                        decoder.Decode1D(outBuf, im, 0, height);
                        g4.Fax4Encode(outBuf, height);
                        break;

                    case TIFFConstants.COMPRESSION_CCITTFAX3:
                        try {
                            decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                        }
                        catch (Exception e) {
                            // let's flip the fill bits and try again...
                            tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS;
                            try {
                                decoder.Decode2D(outBuf, im, 0, height, tiffT4Options);
                            }
                            catch {
                                throw e;
                            }
                        }
                        g4.Fax4Encode(outBuf, height);
                        break;

                    case TIFFConstants.COMPRESSION_CCITTFAX4:
                        decoder.DecodeT6(outBuf, im, 0, height, tiffT6Options);
                        g4.Fax4Encode(outBuf, height);
                        break;
                    }
                    rowsLeft -= rowsStrip;
                }
                byte[] g4pic = g4.Close();
                img = Image.GetInstance(w, h, false, Image.CCITTG4, paramsn & Image.CCITT_BLACKIS1, g4pic);
            }
            img.SetDpi(dpiX, dpiY);
            img.XYRatio = XYRatio;
            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
            {
                try {
                    TIFFField   fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                    ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                    if (icc_prof.NumComponents == 1)
                    {
                        img.TagICC = icc_prof;
                    }
                }
                catch {
                    //empty
                }
            }
            img.OriginalType = Image.ORIGINAL_TIFF;
            if (rotation != 0)
            {
                img.InitialRotation = rotation;
            }
            return(img);
        }
Ejemplo n.º 28
0
        // private methods

        /// <summary>
        /// This method checks if the image is a valid JPEG and processes some parameters.
        /// </summary>
        private void ProcessParameters()
        {
            type         = Element.JPEG;
            originalType = ORIGINAL_JPEG;
            Stream istr = null;

            try {
                string errorID;
                if (rawData == null)
                {
                    WebRequest w = WebRequest.Create(url);
                    w.Credentials = CredentialCache.DefaultCredentials;
                    istr          = w.GetResponse().GetResponseStream();
                    errorID       = url.ToString();
                }
                else
                {
                    istr    = new MemoryStream(rawData);
                    errorID = "Byte array";
                }
                if (istr.ReadByte() != 0xFF || istr.ReadByte() != 0xD8)
                {
                    throw new BadElementException(MessageLocalization.GetComposedMessage("1.is.not.a.valid.jpeg.file", errorID));
                }
                bool firstPass = true;
                int  len;
                while (true)
                {
                    int v = istr.ReadByte();
                    if (v < 0)
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("premature.eof.while.reading.jpg"));
                    }
                    if (v == 0xFF)
                    {
                        int marker = istr.ReadByte();
                        if (firstPass && marker == M_APP0)
                        {
                            firstPass = false;
                            len       = GetShort(istr);
                            if (len < 16)
                            {
                                Utilities.Skip(istr, len - 2);
                                continue;
                            }
                            byte[] bcomp = new byte[JFIF_ID.Length];
                            int    r     = istr.Read(bcomp, 0, bcomp.Length);
                            if (r != bcomp.Length)
                            {
                                throw new BadElementException(MessageLocalization.GetComposedMessage("1.corrupted.jfif.marker", errorID));
                            }
                            bool found = true;
                            for (int k = 0; k < bcomp.Length; ++k)
                            {
                                if (bcomp[k] != JFIF_ID[k])
                                {
                                    found = false;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                Utilities.Skip(istr, len - 2 - bcomp.Length);
                                continue;
                            }
                            Utilities.Skip(istr, 2);
                            int units = istr.ReadByte();
                            int dx    = GetShort(istr);
                            int dy    = GetShort(istr);
                            if (units == 1)
                            {
                                dpiX = dx;
                                dpiY = dy;
                            }
                            else if (units == 2)
                            {
                                dpiX = (int)((float)dx * 2.54f + 0.5f);
                                dpiY = (int)((float)dy * 2.54f + 0.5f);
                            }
                            Utilities.Skip(istr, len - 2 - bcomp.Length - 7);
                            continue;
                        }
                        if (marker == M_APPE)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteappe = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                byteappe[k] = (byte)istr.ReadByte();
                            }
                            if (byteappe.Length >= 12)
                            {
                                string appe = System.Text.ASCIIEncoding.ASCII.GetString(byteappe, 0, 5);
                                if (Util.EqualsIgnoreCase(appe, "adobe"))
                                {
                                    invert = true;
                                }
                            }
                            continue;
                        }
                        if (marker == M_APP2)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteapp2 = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                byteapp2[k] = (byte)istr.ReadByte();
                            }
                            if (byteapp2.Length >= 14)
                            {
                                String app2 = System.Text.ASCIIEncoding.ASCII.GetString(byteapp2, 0, 11);
                                if (app2.Equals("ICC_PROFILE"))
                                {
                                    int order = byteapp2[12] & 0xff;
                                    int count = byteapp2[13] & 0xff;
                                    // some jpeg producers don't know how to count to 1
                                    if (order < 1)
                                    {
                                        order = 1;
                                    }
                                    if (count < 1)
                                    {
                                        count = 1;
                                    }
                                    if (icc == null)
                                    {
                                        icc = new byte[count][];
                                    }
                                    icc[order - 1] = byteapp2;
                                }
                            }
                            continue;
                        }
                        firstPass = false;
                        int markertype = MarkerType(marker);
                        if (markertype == VALID_MARKER)
                        {
                            Utilities.Skip(istr, 2);
                            if (istr.ReadByte() != 0x08)
                            {
                                throw new BadElementException(MessageLocalization.GetComposedMessage("1.must.have.8.bits.per.component", errorID));
                            }
                            scaledHeight = GetShort(istr);
                            Top          = scaledHeight;
                            scaledWidth  = GetShort(istr);
                            Right        = scaledWidth;
                            colorspace   = istr.ReadByte();
                            bpc          = 8;
                            break;
                        }
                        else if (markertype == UNSUPPORTED_MARKER)
                        {
                            throw new BadElementException(MessageLocalization.GetComposedMessage("1.unsupported.jpeg.marker.2", errorID, marker));
                        }
                        else if (markertype != NOPARAM_MARKER)
                        {
                            Utilities.Skip(istr, GetShort(istr) - 2);
                        }
                    }
                }
            }
            finally {
                if (istr != null)
                {
                    istr.Close();
                }
            }
            plainWidth  = this.Width;
            plainHeight = this.Height;
            if (icc != null)
            {
                int total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    if (icc[k] == null)
                    {
                        icc = null;
                        return;
                    }
                    total += icc[k].Length - 14;
                }
                byte[] ficc = new byte[total];
                total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    System.Array.Copy(icc[k], 14, ficc, total, icc[k].Length - 14);
                    total += icc[k].Length - 14;
                }
                try {
                    ICC_Profile icc_prof = ICC_Profile.GetInstance(ficc);
                    TagICC = icc_prof;
                }
                catch {}
                icc = null;
            }
        }
Ejemplo n.º 29
0
        // private methods

        /// <summary>
        /// This method checks if the image is a valid JPEG and processes some parameters.
        /// </summary>
        private void ProcessParameters()
        {
            type         = Element.JPEG;
            originalType = ORIGINAL_JPEG;
            Stream istr = null;

            try {
                string errorID;
                if (rawData == null)
                {
                    WebRequest w = WebRequest.Create(url);
                    w.Credentials = CredentialCache.DefaultCredentials;
                    istr          = w.GetResponse().GetResponseStream();
                    errorID       = url.ToString();
                }
                else
                {
                    istr    = new MemoryStream(rawData);
                    errorID = "Byte array";
                }
                if (istr.ReadByte() != 0xFF || istr.ReadByte() != 0xD8)
                {
                    throw new BadElementException(MessageLocalization.GetComposedMessage("1.is.not.a.valid.jpeg.file", errorID));
                }
                bool firstPass = true;
                int  len;
                while (true)
                {
                    int v = istr.ReadByte();
                    if (v < 0)
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("premature.eof.while.reading.jpg"));
                    }
                    if (v == 0xFF)
                    {
                        int marker = istr.ReadByte();
                        if (firstPass && marker == M_APP0)
                        {
                            firstPass = false;
                            len       = GetShort(istr);
                            if (len < 16)
                            {
                                Utilities.Skip(istr, len - 2);
                                continue;
                            }
                            byte[] bcomp = new byte[JFIF_ID.Length];
                            int    r     = istr.Read(bcomp, 0, bcomp.Length);
                            if (r != bcomp.Length)
                            {
                                throw new BadElementException(MessageLocalization.GetComposedMessage("1.corrupted.jfif.marker", errorID));
                            }
                            bool found = true;
                            for (int k = 0; k < bcomp.Length; ++k)
                            {
                                if (bcomp[k] != JFIF_ID[k])
                                {
                                    found = false;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                Utilities.Skip(istr, len - 2 - bcomp.Length);
                                continue;
                            }
                            Utilities.Skip(istr, 2);
                            int units = istr.ReadByte();
                            int dx    = GetShort(istr);
                            int dy    = GetShort(istr);
                            if (units == 1)
                            {
                                dpiX = dx;
                                dpiY = dy;
                            }
                            else if (units == 2)
                            {
                                dpiX = (int)((float)dx * 2.54f + 0.5f);
                                dpiY = (int)((float)dy * 2.54f + 0.5f);
                            }
                            Utilities.Skip(istr, len - 2 - bcomp.Length - 7);
                            continue;
                        }
                        if (marker == M_APPE)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteappe = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                byteappe[k] = (byte)istr.ReadByte();
                            }
                            if (byteappe.Length >= 12)
                            {
                                string appe = System.Text.ASCIIEncoding.ASCII.GetString(byteappe, 0, 5);
                                if (Util.EqualsIgnoreCase(appe, "adobe"))
                                {
                                    invert = true;
                                }
                            }
                            continue;
                        }
                        if (marker == M_APP2)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteapp2 = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                byteapp2[k] = (byte)istr.ReadByte();
                            }
                            if (byteapp2.Length >= 14)
                            {
                                String app2 = System.Text.ASCIIEncoding.ASCII.GetString(byteapp2, 0, 11);
                                if (app2.Equals("ICC_PROFILE"))
                                {
                                    int order = byteapp2[12] & 0xff;
                                    int count = byteapp2[13] & 0xff;
                                    // some jpeg producers don't know how to count to 1
                                    if (order < 1)
                                    {
                                        order = 1;
                                    }
                                    if (count < 1)
                                    {
                                        count = 1;
                                    }
                                    if (icc == null)
                                    {
                                        icc = new byte[count][];
                                    }
                                    icc[order - 1] = byteapp2;
                                }
                            }
                            continue;
                        }
                        if (marker == M_APPD)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteappd = new byte[len];
                            for (int k = 0; k < len; k++)
                            {
                                byteappd[k] = (byte)istr.ReadByte();
                            }
                            // search for '8BIM Resolution' marker
                            int j = 0;
                            for (j = 0; j < len - PS_8BIM_RESO.Length; j++)
                            {
                                bool found = true;
                                for (int i = 0; i < PS_8BIM_RESO.Length; i++)
                                {
                                    if (byteappd[j + i] != PS_8BIM_RESO[i])
                                    {
                                        found = false;
                                        break;
                                    }
                                }
                                if (found)
                                {
                                    break;
                                }
                            }

                            j += PS_8BIM_RESO.Length;
                            if (j < len - PS_8BIM_RESO.Length)
                            {
                                // "PASCAL String" for name, i.e. string prefix with length byte
                                // padded to be even length; 2 null bytes if empty
                                byte namelength = byteappd[j];
                                // add length byte
                                namelength++;
                                // add padding
                                if (namelength % 2 == 1)
                                {
                                    namelength++;
                                }
                                // just skip name
                                j += namelength;
                                // size of the resolution data
                                int resosize = (byteappd[j] << 24) + (byteappd[j + 1] << 16) + (byteappd[j + 2] << 8) + byteappd[j + 3];
                                // should be 16
                                if (resosize != 16)
                                {
                                    // fail silently, for now
                                    //System.err.println("DEBUG: unsupported resolution IRB size");
                                    continue;
                                }
                                j += 4;
                                int dx = (byteappd[j] << 8) + (byteappd[j + 1] & 0xff);
                                j += 2;
                                // skip 2 unknown bytes
                                j += 2;
                                int unitsx = (byteappd[j] << 8) + (byteappd[j + 1] & 0xff);
                                j += 2;
                                // skip 2 unknown bytes
                                j += 2;
                                int dy = (byteappd[j] << 8) + (byteappd[j + 1] & 0xff);
                                j += 2;
                                // skip 2 unknown bytes
                                j += 2;
                                int unitsy = (byteappd[j] << 8) + (byteappd[j + 1] & 0xff);

                                if (unitsx == 1 || unitsx == 2)
                                {
                                    dx = (unitsx == 2 ? (int)(dx * 2.54f + 0.5f) : dx);
                                    // make sure this is consistent with JFIF data
                                    if (dpiX != 0 && dpiX != dx)
                                    {
                                        //System.err.println("DEBUG: inconsistent metadata (dpiX: " + dpiX + " vs " + dx + ")");
                                    }
                                    else
                                    {
                                        dpiX = dx;
                                    }
                                }
                                if (unitsy == 1 || unitsy == 2)
                                {
                                    dy = (unitsy == 2 ? (int)(dy * 2.54f + 0.5f) : dy);
                                    // make sure this is consistent with JFIF data
                                    if (dpiY != 0 && dpiY != dy)
                                    {
                                        //System.err.println("DEBUG: inconsistent metadata (dpiY: " + dpiY + " vs " + dy + ")");
                                    }
                                    else
                                    {
                                        dpiY = dy;
                                    }
                                }
                            }
                            continue;
                        }
                        firstPass = false;
                        int markertype = MarkerType(marker);
                        if (markertype == VALID_MARKER)
                        {
                            Utilities.Skip(istr, 2);
                            if (istr.ReadByte() != 0x08)
                            {
                                throw new BadElementException(MessageLocalization.GetComposedMessage("1.must.have.8.bits.per.component", errorID));
                            }
                            scaledHeight = GetShort(istr);
                            Top          = scaledHeight;
                            scaledWidth  = GetShort(istr);
                            Right        = scaledWidth;
                            colorspace   = istr.ReadByte();
                            bpc          = 8;
                            break;
                        }
                        else if (markertype == UNSUPPORTED_MARKER)
                        {
                            throw new BadElementException(MessageLocalization.GetComposedMessage("1.unsupported.jpeg.marker.2", errorID, marker));
                        }
                        else if (markertype != NOPARAM_MARKER)
                        {
                            Utilities.Skip(istr, GetShort(istr) - 2);
                        }
                    }
                }
            }
            finally {
                if (istr != null)
                {
                    istr.Close();
                }
            }
            plainWidth  = this.Width;
            plainHeight = this.Height;
            if (icc != null)
            {
                int total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    if (icc[k] == null)
                    {
                        icc = null;
                        return;
                    }
                    total += icc[k].Length - 14;
                }
                byte[] ficc = new byte[total];
                total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    System.Array.Copy(icc[k], 14, ficc, total, icc[k].Length - 14);
                    total += icc[k].Length - 14;
                }
                try {
                    ICC_Profile icc_prof = ICC_Profile.GetInstance(ficc, colorspace);
                    TagICC = icc_prof;
                }
                catch {}
                icc = null;
            }
        }
Ejemplo n.º 30
0
        protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
        {
            int            predictor   = 1;
            TIFFLZWDecoder lzwDecoder  = null;
            int            compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_NONE:
            case TIFFConstants.COMPRESSION_LZW:
            case TIFFConstants.COMPRESSION_PACKBITS:
            case TIFFConstants.COMPRESSION_DEFLATE:
            case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
            case TIFFConstants.COMPRESSION_OJPEG:
            case TIFFConstants.COMPRESSION_JPEG:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("the.compression.1.is.not.supported", compression));
            }
            int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);

            switch (photometric)
            {
            case TIFFConstants.PHOTOMETRIC_MINISWHITE:
            case TIFFConstants.PHOTOMETRIC_MINISBLACK:
            case TIFFConstants.PHOTOMETRIC_RGB:
            case TIFFConstants.PHOTOMETRIC_SEPARATED:
            case TIFFConstants.PHOTOMETRIC_PALETTE:
                break;

            default:
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("the.photometric.1.is.not.supported", photometric));
                }
                break;
            }
            float rotation = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
            {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) &&
                dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("planar.images.are.not.supported"));
            }
            int extraSamples = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
            {
                extraSamples = 1;
            }
            int samplePerPixel = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
            {
                samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
            }
            int bitsPerSample = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
            {
                bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
            }
            switch (bitsPerSample)
            {
            case 1:
            case 2:
            case 4:
            case 8:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample));
            }
            Image img = null;

            int h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX           = 0;
            int dpiY           = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            }
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            int       fillOrder      = 1;
            bool      reverse        = false;
            TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int rowsStrip = h;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
            {
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            }
            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)   // some TIFF producers are really lousy, so...
            {
                size = new long[] { s.Length - (int)offset[0] };
            }
            if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE)
            {
                TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null)
                {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("illegal.value.for.predictor.in.tiff.file"));
                    }
                    if (predictor == 2 && bitsPerSample != 8)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample));
                    }
                }
            }
            if (compression == TIFFConstants.COMPRESSION_LZW)
            {
                lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel);
            }
            int                   rowsLeft = h;
            MemoryStream          stream   = null;
            MemoryStream          mstream  = null;
            ZDeflaterOutputStream zip      = null;
            ZDeflaterOutputStream mzip     = null;

            if (extraSamples > 0)
            {
                mstream = new MemoryStream();
                mzip    = new ZDeflaterOutputStream(mstream);
            }

            CCITTG4Encoder g4 = null;

            if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
            {
                g4 = new CCITTG4Encoder(w);
            }
            else
            {
                stream = new MemoryStream();
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    zip = new ZDeflaterOutputStream(stream);
                }
            }
            if (compression == TIFFConstants.COMPRESSION_OJPEG)
            {
                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET)))
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("missing.tag.s.for.ojpeg.compression"));
                }
                int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                int jpegLength = (int)s.Length - jpegOffset;

                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT))
                {
                    jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                                 (int)size[0];
                }

                byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                int posFilePointer = (int)s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                // if quantization and/or Huffman tables are stored separately in the tiff,
                // we need to add them to the jpeg data
                TIFFField jpegtables = dir.GetField(TIFFConstants.TIFFTAG_JPEGTABLES);
                if (jpegtables != null)
                {
                    byte[] temp        = jpegtables.GetAsBytes();
                    int    tableoffset = 0;
                    int    tablelength = temp.Length;
                    // remove FFD8 from start
                    if (temp[0] == (byte)0xFF && temp[1] == (byte)0xD8)
                    {
                        tableoffset  = 2;
                        tablelength -= 2;
                    }
                    // remove FFD9 from end
                    if (temp[temp.Length - 2] == (byte)0xFF && temp[temp.Length - 1] == (byte)0xD9)
                    {
                        tablelength -= 2;
                    }
                    byte[] tables = new byte[tablelength];
                    Array.Copy(temp, tableoffset, tables, 0, tablelength);
                    // TODO insert after JFIF header, instead of at the start
                    byte[] jpegwithtables = new byte[jpeg.Length + tables.Length];
                    Array.Copy(jpeg, 0, jpegwithtables, 0, 2);
                    Array.Copy(tables, 0, jpegwithtables, 2, tables.Length);
                    Array.Copy(jpeg, 2, jpegwithtables, tables.Length + 2, jpeg.Length - 2);
                    jpeg = jpegwithtables;
                }
                img = new Jpeg(jpeg);
            }
            else if (compression == TIFFConstants.COMPRESSION_JPEG)
            {
                if (size.Length > 1)
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.Length));
                }
                byte[] jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else
            {
                for (int k = 0; k < offset.Length; ++k)
                {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int    height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TIFFConstants.COMPRESSION_NONE)
                    {
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    }
                    if (reverse)
                    {
                        TIFFFaxDecoder.ReverseBits(im);
                    }
                    switch (compression)
                    {
                    case TIFFConstants.COMPRESSION_DEFLATE:
                    case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                        Inflate(im, outBuf);
                        ApplyPredictor(outBuf, predictor, w, height, samplePerPixel);
                        break;

                    case TIFFConstants.COMPRESSION_NONE:
                        outBuf = im;
                        break;

                    case TIFFConstants.COMPRESSION_PACKBITS:
                        DecodePackbits(im, outBuf);
                        break;

                    case TIFFConstants.COMPRESSION_LZW:
                        lzwDecoder.Decode(im, outBuf, height);
                        break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                    {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else
                    {
                        if (extraSamples > 0)
                        {
                            ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height);
                        }
                        else
                        {
                            zip.Write(outBuf, 0, outBuf.Length);
                        }
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                {
                    img = Image.GetInstance(w, h, false, Image.CCITTG4,
                                            photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else
                {
                    zip.Close();
                    img          = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
            {
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
                {
                    try {
                        TIFFField   fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel - extraSamples == icc_prof.NumComponents)
                        {
                            img.TagICC = icc_prof;
                        }
                    }
                    catch {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP))
                {
                    TIFFField fd      = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                    char[]    rgb     = fd.GetAsChars();
                    byte[]    palette = new byte[rgb.Length];
                    int       gColor  = rgb.Length / 3;
                    int       bColor  = gColor * 2;
                    for (int k = 0; k < gColor; ++k)
                    {
                        palette[k * 3]     = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    // Colormap components are supposed to go from 0 to 655535 but,
                    // as usually, some tiff producers just put values from 0 to 255.
                    // Let's check for these broken tiffs.
                    bool colormapBroken = true;
                    for (int k = 0; k < palette.Length; ++k)
                    {
                        if (palette[k] != 0)
                        {
                            colormapBroken = false;
                            break;
                        }
                    }
                    if (colormapBroken)
                    {
                        for (int k = 0; k < gColor; ++k)
                        {
                            palette[k * 3]     = (byte)rgb[k];
                            palette[k * 3 + 1] = (byte)rgb[k + gColor];
                            palette[k * 3 + 2] = (byte)rgb[k + bColor];
                        }
                    }
                    PdfArray indexed = new PdfArray();
                    indexed.Add(PdfName.INDEXED);
                    indexed.Add(PdfName.DEVICERGB);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    PdfDictionary additional = new PdfDictionary();
                    additional.Put(PdfName.COLORSPACE, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
            {
                img.Inverted = true;
            }
            if (rotation != 0)
            {
                img.InitialRotation = rotation;
            }
            if (extraSamples > 0)
            {
                mzip.Close();
                Image mimg = Image.GetInstance(w, h, 1, bitsPerSample, mstream.ToArray());
                mimg.MakeMask();
                mimg.Deflated = true;
                img.ImageMask = mimg;
            }
            return(img);
        }