Exemple #1
0
        /// <summary>
        /// Updates the links.
        /// </summary>
        /// <param name="pdfFilePath">The PDF file path.</param>
        /// <param name="htmlToPdfFiles">The HTML to PDF files.</param>
        /// <param name="logger">The logger.</param>
        internal static void UpdateLinks(
            string pdfFilePath,
            IReadOnlyCollection <HtmlToPdfFile> htmlToPdfFiles,
            ILogger logger)
        {
            string tempFilePath = Path.GetTempFileName();

            using (PdfReader pdfReader = new PdfReader(pdfFilePath))
            {
                using (PdfWriter pdfWriter = new PdfWriter(tempFilePath))
                {
                    using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader, pdfWriter))
                    {
                        int pageCount = pdfDocument.GetNumberOfPages();
                        for (int i = 1; i <= pageCount; i++)
                        {
                            // get page
                            PdfPage pdfPage = pdfDocument.GetPage(i);

                            // get link annotations
                            IEnumerable <PdfLinkAnnotation> linkAnnotations = pdfPage.GetAnnotations().OfType <PdfLinkAnnotation>();
                            foreach (PdfLinkAnnotation linkAnnotation in linkAnnotations)
                            {
                                // get action
                                PdfDictionary action = linkAnnotation.GetAction();
                                if (action == null)
                                {
                                    continue;
                                }

                                PdfName s = action.GetAsName(PdfName.S);
                                if (s != PdfName.URI)
                                {
                                    continue;
                                }

                                PdfString uriPdfString = action.GetAsString(PdfName.URI);
                                if (!Uri.TryCreate(uriPdfString.GetValue(), UriKind.RelativeOrAbsolute, out Uri uri))
                                {
                                    continue;
                                }

                                if (!uri.IsFile)
                                {
                                    continue;
                                }

                                string htmlFilePath = uri.LocalPath.ToLower();

                                if (!htmlToPdfFiles.Any(x => string.Compare(x.Input, htmlFilePath, StringComparison.OrdinalIgnoreCase) == 0))
                                {
                                    // ex. when printing PDF from TOC.html by itself
                                    logger.LogDebug($"Could not find '{htmlFilePath}'. Referenced in '{pdfFilePath}' on page {i}.");
                                    continue;
                                }

                                HtmlToPdfFile linkedHtmlToPdfFile = htmlToPdfFiles.Single(x => x.Input == htmlFilePath);
                                int           linkedPageNumber    = linkedHtmlToPdfFile.OutputPdfFilePageNumber;

                                PdfPage linkedPage;
                                try
                                {
                                    // http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfDestination.html
                                    linkedPage = pdfDocument.GetPage(linkedPageNumber);
                                }
                                catch (Exception ex)
                                {
                                    throw new PdfPageNotFoundException(linkedPageNumber, linkedHtmlToPdfFile.Input, ex);
                                }

                                float top = linkedPage.GetPageSize().GetTop();
                                PdfExplicitDestination destination = PdfExplicitDestination.CreateFitH(linkedPage, top);
                                PdfAction newAction = PdfAction.CreateGoTo(destination);

                                linkAnnotation.SetAction(newAction);
                            }
                        }
                    }
                }
            }

            File.Delete(pdfFilePath);
            File.Move(tempFilePath, pdfFilePath);
        }
        protected override void CheckPdfObject(PdfWriter writer, int key, Object obj1)
        {
            if (obj1 is PdfNumber)
            {
                PdfNumber number = (PdfNumber)obj1;
                if (Math.Abs(number.DoubleValue) > maxRealValue && number.ToString().Contains("."))
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("real.number.is.out.of.range"));
                }
            }
            else if (obj1 is PdfString)
            {
                PdfString str = (PdfString)obj1;
                if (str.GetBytes().Length > maxStringLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.string.is.too.long"));
                }
            }
            else if (obj1 is PdfArray)
            {
                PdfArray array = (PdfArray)obj1;
                if (array.Size > maxArrayLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.array.exceeds.length.set.by.PDFA1.standard", array.Length.ToString()));
                }
            }
            else if (obj1 is PdfDictionary)
            {
                PdfDictionary dictionary = (PdfDictionary)obj1;
                if (dictionary.Size > maxDictionaryLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.dictionary.is.out.of.bounds"));
                }
                PdfName type = dictionary.GetAsName(PdfName.TYPE);
                if (PdfName.CATALOG.Equals(type))
                {
                    if (!dictionary.Contains(PdfName.METADATA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.contain.metadata"));
                    }

                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.an.aa.entry"));
                    }

                    if (dictionary.Contains(PdfName.NAMES))
                    {
                        PdfDictionary names = GetDirectDictionary(dictionary.Get(PdfName.NAMES));
                        if (names != null && names.Contains(PdfName.EMBEDDEDFILES))
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.embeddedfiles.names.entry"));
                        }
                    }

                    if (CheckStructure(conformanceLevel))
                    {
                        PdfDictionary markInfo = GetDirectDictionary(dictionary.Get(PdfName.MARKINFO));
                        if (markInfo == null || markInfo.GetAsBoolean(PdfName.MARKED) == null || markInfo.GetAsBoolean(PdfName.MARKED).BooleanValue == false)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("document.catalog.dictionary.shall.include.a.markinfo.dictionary.whose.entry.marked.shall.have.a.value.of.true"));
                        }
                        if (!dictionary.Contains(PdfName.LANG))
                        {
                            if (LOGGER.IsLogging(Level.WARN))
                            {
                                LOGGER.Warn(MessageLocalization.GetComposedMessage("document.catalog.dictionary.should.contain.lang.entry"));
                            }
                        }
                    }
                }
                else if (PdfName.PAGE.Equals(type))
                {
                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("page.dictionary.shall.not.include.aa.entry"));
                    }
                }
                else if (PdfName.OUTPUTINTENT.Equals(type))
                {
                    isCheckOutputIntent = true;
                    PdfObject destOutputIntent = dictionary.Get(PdfName.DESTOUTPUTPROFILE);
                    if (destOutputIntent != null && pdfaDestOutputIntent != null)
                    {
                        if (pdfaDestOutputIntent.IndRef != destOutputIntent.IndRef)
                        {
                            throw new PdfAConformanceException(obj1,
                                                               MessageLocalization.GetComposedMessage(
                                                                   "if.outputintents.array.more.than.one.entry.the.same.indirect.object"));
                        }
                    }
                    else
                    {
                        pdfaDestOutputIntent = destOutputIntent;
                    }

                    PdfName gts = dictionary.GetAsName(PdfName.S);
                    if (pdfaDestOutputIntent != null)
                    {
                        if (PdfName.GTS_PDFA1.Equals(gts))
                        {
                            if (pdfaOutputIntentColorSpace != null)
                            {
                                throw new PdfAConformanceException(obj1,
                                                                   MessageLocalization.GetComposedMessage("a.pdfa.file.may.have.only.one.pdfa.outputintent"));
                            }
                            pdfaOutputIntentColorSpace = "";
                            ICC_Profile icc_profile = writer.ColorProfile;
                            pdfaOutputIntentColorSpace = Encoding.GetEncoding("US-ASCII").GetString(icc_profile.Data, 16, 4);
                        }
                    }
                    else
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent"));
                    }
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Finds and sets the page numbers of links mapped to HTML headings in the specified PDF file.
        /// </summary>
        /// <param name="htmlToPdfFile">The HTML to PDF file.</param>
        internal static void SetHeadingPageNumbers(HtmlToPdfFile htmlToPdfFile)
        {
            using (PdfReader pdfReader = new PdfReader(htmlToPdfFile.PdfFilePath))
            {
                using (iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader))
                {
                    int pageCount = pdfDocument.GetNumberOfPages();
                    for (int i = 1; i <= pageCount; i++)
                    {
                        // get page
                        PdfPage pdfPage = pdfDocument.GetPage(i);

                        // get link annotations
                        IEnumerable <PdfLinkAnnotation> linkAnnotations = pdfPage.GetAnnotations().OfType <PdfLinkAnnotation>();
                        foreach (PdfLinkAnnotation linkAnnotation in linkAnnotations)
                        {
                            // get action
                            PdfDictionary action = linkAnnotation.GetAction();
                            if (action == null)
                            {
                                continue;
                            }

                            PdfName s = action.GetAsName(PdfName.S);
                            if (s != PdfName.URI)
                            {
                                continue;
                            }

                            PdfString uriPdfString = action.GetAsString(PdfName.URI);
                            if (!Uri.TryCreate(uriPdfString.GetValue(), UriKind.RelativeOrAbsolute, out Uri uri))
                            {
                                continue;
                            }

                            if (!uri.IsFile)
                            {
                                continue;
                            }

                            // get query string
                            NameValueCollection queryString = HttpUtility.ParseQueryString(uri.Query);

                            // ex. ?headingLevel={level}&headingText
                            string headingLevel = queryString["headingLevel"];
                            if (headingLevel == null)
                            {
                                continue;
                            }

                            if (!int.TryParse(headingLevel, out int level))
                            {
                                continue;
                            }

                            string headingText = queryString["headingText"];
                            if (headingText == null)
                            {
                                continue;
                            }

                            HtmlHeading htmlHeading = htmlToPdfFile.TitleAndHeadings.SingleOrDefault(x => (x.Level == level) && (x.Text == headingText));
                            if (htmlHeading == null)
                            {
                                continue;
                            }

                            htmlHeading.Page = i;
                        }
                    }
                }
            }
        }
Exemple #4
0
        public byte[] GetImageAsBytes()
        {
            if (streamBytes == null)
            {
                return(null);
            }
            if (!decoded)
            {
                // if the stream hasn't been decoded, check to see if it is a single stage JPG or JPX encoded stream.  If it is,
                // then we can just use stream as-is
                PdfName filter = dictionary.GetAsName(PdfName.FILTER);
                if (filter == null)
                {
                    PdfArray filterArray = dictionary.GetAsArray(PdfName.FILTER);
                    if (filterArray.Size == 1)
                    {
                        filter = filterArray.GetAsName(0);
                    }
                    else
                    {
                        throw new UnsupportedPdfException("Multi-stage filters not supported here (" + filterArray + ")");
                    }
                }
                if (PdfName.DCTDECODE.Equals(filter))
                {
                    fileType = TYPE_JPG;
                    return(streamBytes);
                }
                else if (PdfName.JPXDECODE.Equals(filter))
                {
                    fileType = TYPE_JP2;
                    return(streamBytes);
                }
                throw new UnsupportedPdfException("Unsupported stream filter " + filter);
            }
            pngColorType = -1;
            width        = dictionary.GetAsNumber(PdfName.WIDTH).IntValue;
            height       = dictionary.GetAsNumber(PdfName.HEIGHT).IntValue;
            bpc          = dictionary.GetAsNumber(PdfName.BITSPERCOMPONENT).IntValue;
            pngBitDepth  = bpc;
            PdfObject colorspace = dictionary.GetDirectObject(PdfName.COLORSPACE);

            palette = null;
            icc     = null;
            stride  = 0;
            FindColorspace(colorspace, true);
            MemoryStream ms = new MemoryStream();

            if (pngColorType < 0)
            {
                if (bpc != 8)
                {
                    return(null);
                }
                if (PdfName.DEVICECMYK.Equals(colorspace))
                {
                }
                else if (colorspace is PdfArray)
                {
                    PdfArray  ca   = (PdfArray)colorspace;
                    PdfObject tyca = ca.GetDirectObject(0);
                    if (!PdfName.ICCBASED.Equals(tyca))
                    {
                        return(null);
                    }
                    PRStream pr = (PRStream)ca.GetDirectObject(1);
                    int      n  = pr.GetAsNumber(PdfName.N).IntValue;
                    if (n != 4)
                    {
                        return(null);
                    }
                    icc = PdfReader.GetStreamBytes(pr);
                }
                else
                {
                    return(null);
                }
                stride = 4 * width;
                TiffWriter wr = new TiffWriter();
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL, 4));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_BITSPERSAMPLE, new int[] { 8, 8, 8, 8 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PHOTOMETRIC, TIFFConstants.PHOTOMETRIC_SEPARATED));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGEWIDTH, width));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, height));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_COMPRESSION, TIFFConstants.COMPRESSION_LZW));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PREDICTOR, TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP, height));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_XRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_YRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_RESOLUTIONUNIT, TIFFConstants.RESUNIT_INCH));
                wr.AddField(new TiffWriter.FieldAscii(TIFFConstants.TIFFTAG_SOFTWARE, Document.Version));
                MemoryStream comp = new MemoryStream();
                TiffWriter.CompressLZW(comp, 2, streamBytes, height, 4, stride);
                byte[] buf = comp.ToArray();
                wr.AddField(new TiffWriter.FieldImage(buf));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_STRIPBYTECOUNTS, buf.Length));
                if (icc != null)
                {
                    wr.AddField(new TiffWriter.FieldUndefined(TIFFConstants.TIFFTAG_ICCPROFILE, icc));
                }
                wr.WriteFile(ms);
                fileType = TYPE_TIF;
                return(ms.ToArray());
            }
            PngWriter png = new PngWriter(ms);

            png.WriteHeader(width, height, pngBitDepth, pngColorType);
            if (icc != null)
            {
                png.WriteIccProfile(icc);
            }
            if (palette != null)
            {
                png.WritePalette(palette);
            }
            png.WriteData(streamBytes, stride);
            png.WriteEnd();
            fileType = TYPE_PNG;
            return(ms.ToArray());
        }
Exemple #5
0
        static void Main(string[] args)
        {
            string pdfFile     = "";
            string outputDir   = "";
            bool   interactive = false;

            foreach (string arg in args)
            {
                switch (arg.Substring(0, 2).ToLower())
                {
                case "-o":
                    outputDir = arg.Substring(3);
                    if (!Directory.Exists(outputDir))
                    {
                        Directory.CreateDirectory(outputDir);
                    }
                    if (!Directory.Exists(outputDir))
                    {
                        Console.WriteLine("Unable to create directory: " + outputDir);
                        PrintHelp();
                        return;
                    }
                    break;

                case "-h":
                    PrintHelp();
                    break;

                case "-i":
                    interactive = true;
                    break;

                default:
                    pdfFile = arg;
                    break;
                }
            }

            // read the supplied PDF
            PdfReader pdf = new PdfReader(pdfFile);
            // for every file type in the PDF in every page, build a list of tuples containing the potential attachment
            List <Tuple <string, byte[]> > files = new List <Tuple <string, byte[]> >();
            int foundItems = 0;

            for (int i = 1; i <= pdf.NumberOfPages; i++)
            {
                PdfArray arr = pdf.GetPageN(i).GetAsArray(PdfName.ANNOTS);
                if (arr == null)
                {
                    continue;
                }
                for (int j = 0; j < arr.Size; j++)
                {
                    //get every reference on this page and see if it's an attachment
                    PdfDictionary annot = arr.GetAsDict(j);
                    if (PdfName.FILEATTACHMENT.Equals(annot.GetAsName(PdfName.SUBTYPE)))
                    {
                        PdfDictionary fs   = annot.GetAsDict(PdfName.FS);
                        PdfDictionary refs = fs.GetAsDict(PdfName.EF);
                        foreach (PdfName name in refs.Keys)
                        {
                            //found a file! Store it.
                            foundItems++;
                            string n = fs.GetAsString(name).ToString();
                            Console.WriteLine("[" + foundItems.ToString() + "] " + n);
                            files.Add(new Tuple <string, byte[]>(n, PdfReader.GetStreamBytes((PRStream)refs.GetAsStream(name))));
                        }
                    }
                }
            }
            //allow the user to select which file to save
            if (interactive)
            {
                bool ret = true;
                while (ret)
                {
                    Console.Write("Enter the number of the file you want to save (or 0 to quit): ");
                    int i = 0;
                    if (int.TryParse(Console.ReadLine(), out i))
                    {
                        if (i > 0 && i <= files.Count)
                        {
                            i--;
                            using (FileStream fs = new FileStream(Path.Combine(outputDir, files[i].Item1), FileMode.Create, FileAccess.Write))
                            {
                                fs.Write(files[i].Item2, 0, files[i].Item2.Length);
                            }
                        }
                    }
                    if (i < 0)
                    {
                        ret = false;
                    }
                }
            }
            else //or save all files in the specified directory (will overwrite)
            {
                foreach (var file in files)
                {
                    using (FileStream fs = new FileStream(Path.Combine(outputDir, file.Item1), FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(file.Item2, 0, file.Item2.Length);
                    }
                }
            }
        }
Exemple #6
0
 protected virtual void CheckEmbeddedFile(PdfDictionary embeddedFile) {
     PdfName subtype = embeddedFile.GetAsName(PdfName.SUBTYPE);
     if (subtype == null || !MimeTypePdf.Equals(subtype)) {
         throw new PdfAConformanceException(embeddedFile, MessageLocalization.GetComposedMessage("embedded.file.shall.contain.pdf.mime.type"));
     }
 }
        private void FillFields(AcroFields acroFields)
        {
            var fields = new LinkedDictionary <string, AcroFields.Item>();

            typeof(AcroFields).GetField("fields", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(acroFields, fields);

            PdfDictionary top = (PdfDictionary)GetPdfObjectRelease(Catalog.Get(PdfName.ACROFORM));

            if (top == null)
            {
                return;
            }
            PdfArray arrfds = (PdfArray)GetPdfObjectRelease(top.Get(PdfName.FIELDS));

            if (arrfds == null || arrfds.Size == 0)
            {
                return;
            }
            for (int k = 1; k <= NumberOfPages; ++k)
            {
                PdfDictionary page   = GetPageNRelease(k);
                PdfArray      annots = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.ANNOTS), page);
                if (annots == null)
                {
                    continue;
                }
                for (int j = 0; j < annots.Size; ++j)
                {
                    PdfDictionary annot = annots.GetAsDict(j);
                    if (annot == null)
                    {
                        ReleaseLastXrefPartial(annots.GetAsIndirectObject(j));
                        continue;
                    }
                    if (!PdfName.WIDGET.Equals(annot.GetAsName(PdfName.SUBTYPE)))
                    {
                        ReleaseLastXrefPartial(annots.GetAsIndirectObject(j));
                        continue;
                    }
                    PdfDictionary widget = annot;
                    PdfDictionary dic    = new PdfDictionary();
                    dic.Merge(annot);
                    string        name  = string.Empty;
                    PdfDictionary value = null;
                    PdfObject     lastV = null;
                    while (annot != null)
                    {
                        dic.Merge(annot);
                        PdfString t = annot.GetAsString(PdfName.T);
                        if (t != null)
                        {
                            name = t.ToUnicodeString() + "." + name;
                        }
                        if (lastV == null && annot.Get(PdfName.V) != null)
                        {
                            lastV = GetPdfObjectRelease(annot.Get(PdfName.V));
                        }
                        if (value == null && t != null)
                        {
                            value = annot;
                            if (annot.Get(PdfName.V) == null && lastV != null)
                            {
                                value.Put(PdfName.V, lastV);
                            }
                        }
                        annot = annot.GetAsDict(PdfName.PARENT);
                    }
                    if (name.Length > 0)
                    {
                        name = name.Substring(0, name.Length - 1);
                    }
                    AcroFields.Item item;
                    if (!fields.TryGetValue(name, out item))
                    {
                        item         = new AcroFields.Item();
                        fields[name] = item;
                    }
                    var addValueMethod = item.GetType().GetMethod("AddValue", BindingFlags.Instance | BindingFlags.NonPublic);
                    if (value == null)
                    {
                        addValueMethod.Invoke(item, new object[] { widget });
                    }
                    else
                    {
                        addValueMethod.Invoke(item, new object[] { value });
                    }
                    item.GetType().GetMethod("AddWidget", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { widget });
                    item.GetType().GetMethod("AddWidgetRef", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { annots.GetAsIndirectObject(j) });                     // must be a reference
                    if (top != null)
                    {
                        dic.MergeDifferent(top);
                    }
                    item.GetType().GetMethod("AddMerged", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                    item.GetType().GetMethod("AddPage", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { k });
                    item.GetType().GetMethod("AddTabOrder", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { j });
                }
            }
            // some tools produce invisible signatures without an entry in the page annotation array
            // look for a single level annotation
            PdfNumber sigFlags = top.GetAsNumber(PdfName.SIGFLAGS);

            if (sigFlags == null || (sigFlags.IntValue & 1) != 1)
            {
                return;
            }
            for (int j = 0; j < arrfds.Size; ++j)
            {
                PdfDictionary annot = arrfds.GetAsDict(j);
                if (annot == null)
                {
                    ReleaseLastXrefPartial(arrfds.GetAsIndirectObject(j));
                    continue;
                }
                if (!PdfName.WIDGET.Equals(annot.GetAsName(PdfName.SUBTYPE)))
                {
                    ReleaseLastXrefPartial(arrfds.GetAsIndirectObject(j));
                    continue;
                }
                PdfArray kids = (PdfArray)GetPdfObjectRelease(annot.Get(PdfName.KIDS));
                if (kids != null)
                {
                    continue;
                }
                PdfDictionary dic = new PdfDictionary();
                dic.Merge(annot);
                PdfString t = annot.GetAsString(PdfName.T);
                if (t == null)
                {
                    continue;
                }
                string name = t.ToUnicodeString();
                if (fields.ContainsKey(name))
                {
                    continue;
                }
                var item = new AcroFields.Item();
                fields[name] = item;
                item.GetType().GetMethod("AddValue", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                item.GetType().GetMethod("AddWidget", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                item.GetType().GetMethod("AddWidgetRef", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { arrfds.GetAsIndirectObject(j) });                 // must be a reference
                item.GetType().GetMethod("AddMerged", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { dic });
                item.GetType().GetMethod("AddPage", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { -1 });
                item.GetType().GetMethod("AddTabOrder", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[] { -1 });
            }
        }
Exemple #8
0
        public byte[] Add(string infile, string outFile)
        {
            PdfFont   baseFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
            Rectangle pageSize;
            string    NoOfPagesPadded = string.Empty;
            string    PageNoPadded    = string.Empty;
            string    HdrLeft         = string.Empty;
            string    HdrRight        = string.Empty;

            int xLeft  = 30;
            int xRight = 110;  //was 100
            int xTop   = 30;

            float watermarkTrimmingRectangleWidth;  //= 300;
            float watermarkTrimmingRectangleHeight = 300;

            float formXOffset = 0;
            float formYOffset = -5;  // was zero  set to -5 because dangling letters (e.g. g) were being cut-off

            byte[] outByteFile;
            byte[] inByteFile = null;

            try
            {
                inByteFile = File.ReadAllBytes(infile);
                IRandomAccessSource inSourceFile = new RandomAccessSourceFactory().CreateSource(inByteFile);
                using (PdfReader reader = new PdfReader(inSourceFile, new ReaderProperties()).SetUnethicalReading(true))
                {
                    using (var outMemoryFile = new MemoryStream())
                    {
                        using (PdfWriter pdfWrite = new PdfWriter(outMemoryFile))
                        {
                            using (PdfDocument pdfDoc = new PdfDocument(reader, pdfWrite))
                            {
                                using (Document doc = new Document(pdfDoc))
                                {
                                    int n = pdfDoc.GetNumberOfPages();
                                    for (var i = 1; i <= n; i++)
                                    {
                                        // Remove annotation if it exists
                                        PdfDictionary pageDict = pdfDoc.GetPage(i).GetPdfObject();
                                        PdfArray      annots   = pageDict.GetAsArray(PdfName.Annots);
                                        if (annots != null)
                                        {
                                            for (int j = 0; j < annots.Size(); j++)
                                            {
                                                PdfDictionary annotation = annots.GetAsDictionary(j);
                                                if (PdfName.Watermark.Equals(annotation.GetAsName(PdfName.Subtype)))
                                                {
                                                    string NMvalue = annotation.GetAsString(PdfName.NM).GetValue();
                                                    if (NMvalue == AnnotName)
                                                    {
                                                        annotation.Clear();
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    for (int i = 1; i <= n; i++)
                                    {
                                        PdfPage page = pdfDoc.GetPage(i);
                                        pageSize = page.GetMediaBox();

                                        watermarkTrimmingRectangleWidth = pageSize.GetWidth();
                                        float     PageWidth  = pageSize.GetWidth();
                                        float     PageHeight = pageSize.GetHeight();
                                        int       rotation   = page.GetRotation();
                                        Rectangle watermarkTrimmingRectangle = new Rectangle(pageSize.GetLeft() + xLeft, pageSize.GetTop() - xTop, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight);

                                        PdfWatermarkAnnotation watermark = new PdfWatermarkAnnotation(watermarkTrimmingRectangle);

                                        watermark.SetName(new PdfString(AnnotName));
                                        Rectangle formRectangle = new Rectangle(formXOffset, formYOffset, watermarkTrimmingRectangleWidth, watermarkTrimmingRectangleHeight);

                                        PdfFormXObject form       = new PdfFormXObject(formRectangle); //Observation: font XObject will be resized to fit inside the watermark rectangle.  If it is larger, your text will be stretched.
                                        PdfCanvas      canvasOver = new PdfCanvas(form, pdfDoc);

                                        canvasOver.SetFillColor(iText.Kernel.Colors.ColorConstants.RED);
                                        canvasOver.SetFontAndSize(baseFont, 10);
                                        canvasOver.SaveState();

                                        string SDSNo = "z2345678";
                                        HdrLeft = CompanyName + $" SDS# {SDSNo}";
                                        //  HdrLeft = $"PWidth: {PageWidth.ToString()} rotation: {rotation.ToString()}";  //qqtempqq
                                        NoOfPagesPadded = (n.ToString());
                                        PageNoPadded    = i.ToString();
                                        HdrRight        = $"Page {PageNoPadded} of {NoOfPagesPadded}";
                                        //  HdrRight = $"PHeight: {PageHeight.ToString()}";  //qqtempqq
                                        canvasOver.BeginText()
                                        .SetColor(iText.Kernel.Colors.ColorConstants.RED, true)
                                        .SetFontAndSize(baseFont, 10)
                                        .ShowText(HdrLeft)
                                        .EndText();
                                        canvasOver.BeginText()
                                        .MoveText(formRectangle.GetRight() - xRight, 0)
                                        .SetColor(iText.Kernel.Colors.ColorConstants.RED, true)
                                        .SetFontAndSize(baseFont, 10)
                                        .ShowText(HdrRight)
                                        .EndText();
                                        canvasOver.SaveState();

                                        canvasOver.RestoreState();
                                        canvasOver.Release();

                                        watermark.SetAppearance(PdfName.N, new PdfAnnotationAppearance(form.GetPdfObject()));
                                        watermark.SetFlags(PdfAnnotation.PRINT);

                                        page.AddAnnotation(watermark);
                                    }
                                }
                            }
                            outByteFile = outMemoryFile.ToArray();
                        }
                    }
                }
                File.WriteAllBytes(outFile, outByteFile);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex.ToString());
                return(inByteFile);

                throw;
            }
            return(outByteFile);
        }
        internal PdfType0Font(PdfDictionary fontDictionary)
            : base(fontDictionary)
        {
            newFont = false;
            PdfDictionary cidFont       = fontDictionary.GetAsArray(PdfName.DescendantFonts).GetAsDictionary(0);
            PdfObject     cmap          = fontDictionary.Get(PdfName.Encoding);
            PdfObject     toUnicode     = fontDictionary.Get(PdfName.ToUnicode);
            CMapToUnicode toUnicodeCMap = FontUtil.ProcessToUnicode(toUnicode);

            if (cmap.IsName() && (PdfEncodings.IDENTITY_H.Equals(((PdfName)cmap).GetValue()) || PdfEncodings.IDENTITY_V
                                  .Equals(((PdfName)cmap).GetValue())))
            {
                if (toUnicodeCMap == null)
                {
                    String uniMap = GetUniMapFromOrdering(GetOrdering(cidFont));
                    toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap);
                    if (toUnicodeCMap == null)
                    {
                        toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(PdfEncodings.IDENTITY_H);
                        ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Font.PdfType0Font));
                        logger.Error(MessageFormatUtil.Format(iText.IO.LogMessageConstant.UNKNOWN_CMAP, uniMap));
                    }
                }
                fontProgram  = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap);
                cmapEncoding = CreateCMap(cmap, null);
                System.Diagnostics.Debug.Assert(fontProgram is IDocFontProgram);
                embedded = ((IDocFontProgram)fontProgram).GetFontFile() != null;
            }
            else
            {
                String cidFontName = cidFont.GetAsName(PdfName.BaseFont).GetValue();
                String uniMap      = GetUniMapFromOrdering(GetOrdering(cidFont));
                if (uniMap != null && uniMap.StartsWith("Uni") && CidFontProperties.IsCidFont(cidFontName, uniMap))
                {
                    try {
                        fontProgram  = FontProgramFactory.CreateFont(cidFontName);
                        cmapEncoding = CreateCMap(cmap, uniMap);
                        embedded     = false;
                    }
                    catch (System.IO.IOException) {
                        fontProgram  = null;
                        cmapEncoding = null;
                    }
                }
                else
                {
                    if (toUnicodeCMap == null)
                    {
                        toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap);
                    }
                    if (toUnicodeCMap != null)
                    {
                        fontProgram  = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap);
                        cmapEncoding = CreateCMap(cmap, uniMap);
                    }
                }
                if (fontProgram == null)
                {
                    throw new PdfException(MessageFormatUtil.Format(PdfException.CannotRecogniseDocumentFontWithEncoding, cidFontName
                                                                    , cmap));
                }
            }
            // DescendantFonts is a one-element array specifying the CIDFont dictionary that is the descendant of this Type 0 font.
            PdfDictionary cidFontDictionary = fontDictionary.GetAsArray(PdfName.DescendantFonts).GetAsDictionary(0);
            // Required according to the spec
            PdfName subtype = cidFontDictionary.GetAsName(PdfName.Subtype);

            if (PdfName.CIDFontType0.Equals(subtype))
            {
                cidFontType = CID_FONT_TYPE_0;
            }
            else
            {
                if (PdfName.CIDFontType2.Equals(subtype))
                {
                    cidFontType = CID_FONT_TYPE_2;
                }
                else
                {
                    LogManager.GetLogger(GetType()).Error(iText.IO.LogMessageConstant.FAILED_TO_DETERMINE_CID_FONT_SUBTYPE);
                }
            }
            longTag = new SortedSet <int>();
            subset  = false;
        }
Exemple #10
0
        protected override void CheckPdfObject(PdfWriter writer, int key, Object obj1)
        {
            if (obj1 is PdfNumber)
            {
                PdfNumber number = (PdfNumber)obj1;
                if (Math.Abs(number.DoubleValue) > maxRealValue && number.ToString().Contains("."))
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("real.number.is.out.of.range"));
                }
            }
            else if (obj1 is PdfString)
            {
                PdfString str = (PdfString)obj1;
                if (str.GetBytes().Length > maxStringLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.string.is.too.long"));
                }
            }
            else if (obj1 is PdfArray)
            {
                PdfArray array = (PdfArray)obj1;
                if (array.Size > maxArrayLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.array.is.out.of.bounds"));
                }
            }
            else if (obj1 is PdfDictionary)
            {
                PdfDictionary dictionary = (PdfDictionary)obj1;
                if (dictionary.Size > maxDictionaryLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.dictionary.is.out.of.bounds"));
                }
                PdfName type = dictionary.GetAsName(PdfName.TYPE);
                if (PdfName.CATALOG.Equals(type))
                {
                    if (!dictionary.Contains(PdfName.METADATA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.contain.metadata"));
                    }

                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.an.aa.entry"));
                    }

                    if (dictionary.Contains(PdfName.NAMES))
                    {
                        PdfDictionary names = GetDirectDictionary(dictionary.Get(PdfName.NAMES));
                        if (names != null && names.Contains(PdfName.EMBEDDEDFILES))
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.embeddedfiles.names.entry"));
                        }
                    }

                    if (CheckStructure(conformanceLevel))
                    {
                        PdfDictionary markInfo = GetDirectDictionary(dictionary.Get(PdfName.MARKINFO));
                        if (markInfo == null || markInfo.GetAsBoolean(PdfName.MARKED) == null || markInfo.GetAsBoolean(PdfName.MARKED).BooleanValue == false)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("document.catalog.dictionary.shall.include.a.markinfo.dictionary.whose.entry.marked.shall.have.a.value.of.true"));
                        }
                        if (!dictionary.Contains(PdfName.LANG))
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("document.catalog.dictionary.should.contain.lang.entry"));
                        }
                    }

                    PdfArray outputIntents          = GetDirectArray(dictionary.Get(PdfName.OUTPUTINTENTS));
                    bool     pdfa1OutputIntentFound = false;
                    if (outputIntents != null && outputIntents.Size > 0)
                    {
                        for (int i = 0; i < outputIntents.Size; i++)
                        {
                            PdfDictionary outputIntentDictionary = GetDirectDictionary(outputIntents[i]);
                            PdfName       gts = outputIntentDictionary.GetAsName(PdfName.S);
                            if (PdfName.GTS_PDFA1.Equals(gts))
                            {
                                if (pdfa1OutputIntentFound)
                                {
                                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("a.pdfa.file.may.have.only.one.pdfa.outputintent"));
                                }
                                pdfa1OutputIntentFound = true;
                            }
                            if (outputIntentDictionary != null)
                            {
                                PdfObject destOutputIntent = outputIntentDictionary.Get(PdfName.DESTOUTPUTPROFILE);
                                if (destOutputIntent == null && PdfName.GTS_PDFA1.Equals(gts))
                                {
                                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent"));
                                }
                            }
                        }
                    }

                    if ((rgbUsed || cmykUsed || grayUsed) && !pdfa1OutputIntentFound)
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("if.device.rgb.cmyk.gray.used.in.file.that.file.shall.contain.pdfa.outputintent"));
                    }
                }
                else if (PdfName.PAGE.Equals(type))
                {
                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("page.dictionary.shall.not.include.aa.entry"));
                    }
                }
                else if (PdfName.OUTPUTINTENT.Equals(type))
                {
                    PdfObject iccProfileStream = dictionary.Get(PdfName.DESTOUTPUTPROFILE);
                    String    inputColorSpace  = "";
                    if (iccProfileStream != null)
                    {
                        ICC_Profile icc_profile = writer.ColorProfile;
                        inputColorSpace = Encoding.GetEncoding("US-ASCII").GetString(icc_profile.Data, 16, 4);
                    }
                    PdfName gts = dictionary.GetAsName(PdfName.S);
                    if (!PdfName.GTS_PDFA1.Equals(gts))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent"));
                    }
                    if ("RGB ".Equals(inputColorSpace))
                    {
                        if (cmykUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicecmyk.may.be.used.only.if.the.file.has.a.cmyk.pdfa.outputIntent"));
                        }
                    }
                    else if ("CMYK".Equals(inputColorSpace))
                    {
                        if (rgbUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicergb.may.be.used.only.if.the.file.has.a.rgb.pdfa.outputIntent"));
                        }
                    }
                    else
                    {
                        if (cmykUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicecmyk.may.be.used.only.if.the.file.has.a.cmyk.pdfa.outputIntent"));
                        }
                        if (rgbUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicergb.may.be.used.only.if.the.file.has.a.rgb.pdfa.outputIntent"));
                        }
                    }
                }
            }
        }
        internal static void FillFontDescriptor(iText.Kernel.Font.DocTrueTypeFont font, PdfDictionary fontDesc)
        {
            if (fontDesc == null)
            {
                return;
            }
            PdfNumber v = fontDesc.GetAsNumber(PdfName.Ascent);

            if (v != null)
            {
                font.SetTypoAscender(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.Descent);
            if (v != null)
            {
                font.SetTypoDescender(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.CapHeight);
            if (v != null)
            {
                font.SetCapHeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.XHeight);
            if (v != null)
            {
                font.SetXHeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.ItalicAngle);
            if (v != null)
            {
                font.SetItalicAngle(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.StemV);
            if (v != null)
            {
                font.SetStemV(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.StemH);
            if (v != null)
            {
                font.SetStemH(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.FontWeight);
            if (v != null)
            {
                font.SetFontWeight(v.IntValue());
            }
            v = fontDesc.GetAsNumber(PdfName.MissingWidth);
            if (v != null)
            {
                font.missingWidth = v.IntValue();
            }
            PdfName fontStretch = fontDesc.GetAsName(PdfName.FontStretch);

            if (fontStretch != null)
            {
                font.SetFontWidth(fontStretch.GetValue());
            }
            PdfArray bboxValue = fontDesc.GetAsArray(PdfName.FontBBox);

            if (bboxValue != null)
            {
                int[] bbox = new int[4];
                bbox[0] = bboxValue.GetAsNumber(0).IntValue();
                //llx
                bbox[1] = bboxValue.GetAsNumber(1).IntValue();
                //lly
                bbox[2] = bboxValue.GetAsNumber(2).IntValue();
                //urx
                bbox[3] = bboxValue.GetAsNumber(3).IntValue();
                //ury
                if (bbox[0] > bbox[2])
                {
                    int t = bbox[0];
                    bbox[0] = bbox[2];
                    bbox[2] = t;
                }
                if (bbox[1] > bbox[3])
                {
                    int t = bbox[1];
                    bbox[1] = bbox[3];
                    bbox[3] = t;
                }
                font.SetBbox(bbox);
                // If ascender or descender in font descriptor are zero, we still want to get more or less correct valuee for
                // text extraction, stamping etc. Thus we rely on font bbox in this case
                if (font.GetFontMetrics().GetTypoAscender() == 0 && font.GetFontMetrics().GetTypoDescender() == 0)
                {
                    float maxAscent  = Math.Max(bbox[3], font.GetFontMetrics().GetTypoAscender());
                    float minDescent = Math.Min(bbox[1], font.GetFontMetrics().GetTypoDescender());
                    font.SetTypoAscender((int)(maxAscent * 1000 / (maxAscent - minDescent)));
                    font.SetTypoDescender((int)(minDescent * 1000 / (maxAscent - minDescent)));
                }
            }
            PdfString fontFamily = fontDesc.GetAsString(PdfName.FontFamily);

            if (fontFamily != null)
            {
                font.SetFontFamily(fontFamily.GetValue());
            }
            PdfNumber flagsValue = fontDesc.GetAsNumber(PdfName.Flags);

            if (flagsValue != null)
            {
                int flags = flagsValue.IntValue();
                if ((flags & 1) != 0)
                {
                    font.SetFixedPitch(true);
                }
                if ((flags & 262144) != 0)
                {
                    font.SetBold(true);
                }
            }
            PdfName[] fontFileNames = new PdfName[] { PdfName.FontFile, PdfName.FontFile2, PdfName.FontFile3 };
            foreach (PdfName fontFile in fontFileNames)
            {
                if (fontDesc.ContainsKey(fontFile))
                {
                    font.fontFileName = fontFile;
                    font.fontFile     = fontDesc.GetAsStream(fontFile);
                    break;
                }
            }
        }
Exemple #12
0
        internal static Type1Font CreateFontProgram(PdfDictionary fontDictionary, FontEncoding fontEncoding, CMapToUnicode
                                                    toUnicode)
        {
            PdfName baseFontName = fontDictionary.GetAsName(PdfName.BaseFont);
            String  baseFont;

            if (baseFontName != null)
            {
                baseFont = baseFontName.GetValue();
            }
            else
            {
                baseFont = FontUtil.CreateRandomFontName();
            }
            if (!fontDictionary.ContainsKey(PdfName.FontDescriptor))
            {
                Type1Font type1StdFont;
                try {
                    //if there are no font modifiers, cached font could be used,
                    //otherwise a new instance should be created.
                    type1StdFont = (Type1Font)FontProgramFactory.CreateFont(baseFont, true);
                }
                catch (Exception) {
                    type1StdFont = null;
                }
                if (type1StdFont != null)
                {
                    return(type1StdFont);
                }
            }
            iText.Kernel.Font.DocType1Font fontProgram = new iText.Kernel.Font.DocType1Font(baseFont);
            PdfDictionary fontDesc = fontDictionary.GetAsDictionary(PdfName.FontDescriptor);

            fontProgram.subtype = fontDesc.GetAsName(PdfName.Subtype);
            FillFontDescriptor(fontProgram, fontDesc);
            PdfNumber firstCharNumber = fontDictionary.GetAsNumber(PdfName.FirstChar);
            int       firstChar       = firstCharNumber != null?Math.Max(firstCharNumber.IntValue(), 0) : 0;

            int[] widths = FontUtil.ConvertSimpleWidthsArray(fontDictionary.GetAsArray(PdfName.Widths), firstChar, fontProgram
                                                             .GetMissingWidth());
            fontProgram.avgWidth = 0;
            int glyphsWithWidths = 0;

            for (int i = 0; i < 256; i++)
            {
                Glyph glyph = new Glyph(i, widths[i], fontEncoding.GetUnicode(i));
                fontProgram.codeToGlyph.Put(i, glyph);
                if (glyph.HasValidUnicode())
                {
                    //FontEncoding.codeToUnicode table has higher priority
                    if (fontEncoding.ConvertToByte(glyph.GetUnicode()) == i)
                    {
                        fontProgram.unicodeToGlyph.Put(glyph.GetUnicode(), glyph);
                    }
                }
                else
                {
                    if (toUnicode != null)
                    {
                        glyph.SetChars(toUnicode.Lookup(i));
                    }
                }
                if (widths[i] > 0)
                {
                    glyphsWithWidths++;
                    fontProgram.avgWidth += widths[i];
                }
            }
            if (glyphsWithWidths != 0)
            {
                fontProgram.avgWidth /= glyphsWithWidths;
            }
            return(fontProgram);
        }
Exemple #13
0
        internal PdfType0Font(PdfDictionary fontDictionary)
            : base(fontDictionary)
        {
            CheckFontDictionary(fontDictionary, PdfName.Type0);
            newFont = false;
            PdfDictionary cidFont = fontDictionary.GetAsArray(PdfName.DescendantFonts).GetAsDictionary(0);
            String        cmap    = fontDictionary.GetAsName(PdfName.Encoding).GetValue();

            if (PdfEncodings.IDENTITY_H.Equals(cmap) || PdfEncodings.IDENTITY_V.Equals(cmap))
            {
                PdfObject     toUnicode     = fontDictionary.Get(PdfName.ToUnicode);
                CMapToUnicode toUnicodeCMap = FontUtil.ProcessToUnicode(toUnicode);
                if (toUnicodeCMap == null)
                {
                    String uniMap = GetUniMapFromOrdering(GetOrdering(cidFont));
                    toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap);
                    if (toUnicodeCMap == null)
                    {
                        toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(PdfEncodings.IDENTITY_H);
                        ILogger logger = LoggerFactory.GetLogger(typeof(iText.Kernel.Font.PdfType0Font));
                        logger.Error(String.Format(LogMessageConstant.UNKNOWN_CMAP, uniMap));
                    }
                }
                fontProgram  = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap);
                cmapEncoding = new CMapEncoding(cmap);
                System.Diagnostics.Debug.Assert(fontProgram is IDocFontProgram);
                embedded    = ((IDocFontProgram)fontProgram).GetFontFile() != null;
                cidFontType = CID_FONT_TYPE_2;
            }
            else
            {
                String cidFontName = cidFont.GetAsName(PdfName.BaseFont).GetValue();
                String uniMap      = GetUniMapFromOrdering(GetOrdering(cidFont));
                if (uniMap != null && uniMap.StartsWith("Uni") && CidFontProperties.IsCidFont(cidFontName, uniMap))
                {
                    try {
                        fontProgram  = FontProgramFactory.CreateFont(cidFontName);
                        cmapEncoding = new CMapEncoding(cmap, uniMap);
                        embedded     = false;
                    }
                    catch (System.IO.IOException) {
                        fontProgram  = null;
                        cmapEncoding = null;
                    }
                }
                else
                {
                    CMapToUnicode toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap);
                    if (toUnicodeCMap != null)
                    {
                        fontProgram  = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap);
                        cmapEncoding = new CMapEncoding(cmap, uniMap);
                    }
                }
                if (fontProgram == null)
                {
                    throw new PdfException(String.Format("Cannot recognise document font {0} with {1} encoding", cidFontName,
                                                         cmap));
                }
                cidFontType = CID_FONT_TYPE_0;
            }
            longTag = new LinkedDictionary <int, int[]>();
            subset  = false;
        }
Exemple #14
0
        public static Dictionary <string, object> GetAnnotationsFromPDF(string filepath, int page = 1)
        {
            if (!System.IO.File.Exists(filepath))
            {
                throw new Exception(Properties.Resources.FileNotFoundError);
            }

            List <Content.Annotation> elements = new List <Content.Annotation>();

            Rectangle pagesize = null;

            // Open a new memory stream
            using (var ms = new System.IO.MemoryStream())
            {
                // Create a new pdf reader and get the first page
                PdfReader myPdfReader = new PdfReader(filepath);

                if (page < 1 || page > myPdfReader.NumberOfPages)
                {
                    throw new Exception(Properties.Resources.WrongPageNumber);
                }

                PdfDictionary pageDict   = myPdfReader.GetPageN(page);
                PdfArray      annotArray = pageDict.GetAsArray(PdfName.ANNOTS);
                pagesize = myPdfReader.GetPageSizeWithRotation(page).ToDSRectangle();

                if (annotArray == null)
                {
                    throw new Exception(Properties.Resources.NoAnnotations);
                }

                // Walk through the annotation element array
                for (int i = 0; i < annotArray.Size; i++)
                {
                    // Get the elements type and subject to filter by
                    PdfDictionary annotationElement = annotArray.GetAsDict(i);
                    PdfName       subtype           = annotationElement.GetAsName(PdfName.SUBTYPE);
                    if (subtype != null)
                    {
                        if (subtype == PdfName.LINE)
                        {
                            elements.Add(annotationElement.ToLine());
                        }
                        else if (subtype == PdfName.POLYGON)
                        {
                            elements.Add(annotationElement.ToPolyCurve(true));
                        }
                        else if (subtype == PdfName.POLYLINE)
                        {
                            elements.Add(annotationElement.ToPolyCurve(false));
                        }
                        else if (subtype == PdfName.INK)
                        {
                            elements.Add(annotationElement.InkToPolyCurve());
                        }
                        else if (subtype == PdfName.SQUARE)
                        {
                            elements.Add(annotationElement.ToRectangle());
                        }
                        else if (subtype == PdfName.FREETEXT)
                        {
                            elements.Add(annotationElement.ToRectangle());
                        }
                        else if (subtype == PdfName.CIRCLE)
                        {
                            elements.Add(annotationElement.ToCircle());
                        }
                    }
                }

                string content = PdfTextExtractor.GetTextFromPage(myPdfReader, page, new SimpleTextExtractionStrategy());
            }

            return(new Dictionary <string, object>()
            {
                { "Annotations", elements },
                { "Rectangle", pagesize }
            });
        }
Exemple #15
0
        /**
         * @param colorSpaceName the name of the color space. If null, a bi-tonal (black and white) color space is assumed.
         * @return the components per pixel for the specified color space
         */
        private static int GetComponentsPerPixel(PdfName colorSpaceName, PdfDictionary colorSpaceDic){
            if (colorSpaceName == null)
                return 1;
            if (colorSpaceName.Equals(PdfName.DEVICEGRAY))
                return 1;
            if (colorSpaceName.Equals(PdfName.DEVICERGB))
                return 3;
            if (colorSpaceName.Equals(PdfName.DEVICECMYK))
                return 4;
            
            if (colorSpaceDic != null){
                PdfArray colorSpace = colorSpaceDic.GetAsArray(colorSpaceName);
                if (colorSpace != null){
                    if (PdfName.INDEXED.Equals(colorSpace.GetAsName(0))){
                        return 1;
                    }
                }
                else {
                    PdfName tempName = colorSpaceDic.GetAsName(colorSpaceName);
                    if(tempName != null) {
                        return GetComponentsPerPixel(tempName, colorSpaceDic);
                    }
                }
            }

            throw new ArgumentException("Unexpected color space " + colorSpaceName);
        }
Exemple #16
0
        protected internal override void CheckAnnotation(PdfDictionary annotDic)
        {
            PdfName subtype = annotDic.GetAsName(PdfName.Subtype);

            if (subtype == null)
            {
                throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_TYPE_0_IS_NOT_PERMITTED).SetMessageParams
                          ("null");
            }
            if (forbiddenAnnotations.Contains(subtype))
            {
                throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_TYPE_0_IS_NOT_PERMITTED).SetMessageParams
                          (subtype.GetValue());
            }
            PdfNumber ca = annotDic.GetAsNumber(PdfName.CA);

            if (ca != null && ca.FloatValue() != 1.0)
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_THE_CA_KEY_WITH_A_VALUE_OTHER_THAN_1
                                                   );
            }
            if (!annotDic.ContainsKey(PdfName.F))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_CONTAIN_THE_F_KEY
                                                   );
            }
            int flags = (int)annotDic.GetAsInt(PdfName.F);

            if (!CheckFlag(flags, PdfAnnotation.PRINT) || CheckFlag(flags, PdfAnnotation.HIDDEN) || CheckFlag(flags, PdfAnnotation
                                                                                                              .INVISIBLE) || CheckFlag(flags, PdfAnnotation.NO_VIEW))
            {
                throw new PdfAConformanceException(PdfAConformanceException.THE_F_KEYS_PRINT_FLAG_BIT_SHALL_BE_SET_TO_1_AND_ITS_HIDDEN_INVISIBLE_AND_NOVIEW_FLAG_BITS_SHALL_BE_SET_TO_0
                                                   );
            }
            if (subtype.Equals(PdfName.Text) && (!CheckFlag(flags, PdfAnnotation.NO_ZOOM) || !CheckFlag(flags, PdfAnnotation
                                                                                                        .NO_ROTATE)))
            {
                throw new PdfAConformanceException(PdfAConformanceLogMessageConstant.TEXT_ANNOTATIONS_SHOULD_SET_THE_NOZOOM_AND_NOROTATE_FLAG_BITS_OF_THE_F_KEY_TO_1
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.C) || annotDic.ContainsKey(PdfName.IC))
            {
                if (!ICC_COLOR_SPACE_RGB.Equals(pdfAOutputIntentColorSpace))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.DESTOUTPUTPROFILE_IN_THE_PDFA1_OUTPUTINTENT_DICTIONARY_SHALL_BE_RGB
                                                       );
                }
            }
            PdfDictionary ap = annotDic.GetAsDictionary(PdfName.AP);

            if (ap != null)
            {
                if (ap.ContainsKey(PdfName.D) || ap.ContainsKey(PdfName.R))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE
                                                       );
                }
                if (PdfName.Widget.Equals(annotDic.GetAsName(PdfName.Subtype)) && PdfName.Btn.Equals(annotDic.GetAsName(PdfName
                                                                                                                        .FT)))
                {
                    if (ap.GetAsDictionary(PdfName.N) == null)
                    {
                        throw new PdfAConformanceException(PdfAConformanceException.N_KEY_SHALL_BE_APPEARANCE_SUBDICTIONARY);
                    }
                }
                else
                {
                    if (ap.GetAsStream(PdfName.N) == null)
                    {
                        throw new PdfAConformanceException(PdfAConformanceException.APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE
                                                           );
                    }
                }
                CheckResourcesOfAppearanceStreams(ap);
            }
            if (PdfName.Widget.Equals(subtype) && (annotDic.ContainsKey(PdfName.AA) || annotDic.ContainsKey(PdfName.A)
                                                   ))
            {
                throw new PdfAConformanceException(PdfAConformanceException.WIDGET_ANNOTATION_DICTIONARY_OR_FIELD_DICTIONARY_SHALL_NOT_INCLUDE_A_OR_AA_ENTRY
                                                   );
            }
            if (annotDic.ContainsKey(PdfName.AA))
            {
                throw new PdfAConformanceException(PdfAConformanceException.AN_ANNOTATION_DICTIONARY_SHALL_NOT_CONTAIN_AA_KEY
                                                   );
            }
            if (CheckStructure(conformanceLevel))
            {
                if (contentAnnotations.Contains(subtype) && !annotDic.ContainsKey(PdfName.Contents))
                {
                    throw new PdfAConformanceException(PdfAConformanceException.ANNOTATION_OF_TYPE_0_SHOULD_HAVE_CONTENTS_KEY)
                          .SetMessageParams(subtype.GetValue());
                }
            }
        }
Exemple #17
0
 /**
  * Computes the number of unfiltered bytes that each row of the image will contain.
  * If the number of bytes results in a partial terminating byte, this number is rounded up
  * per the PDF specification
  * @param imageDictionary the dictionary of the inline image
  * @return the number of bytes per row of the image
  */
 private static int ComputeBytesPerRow(PdfDictionary imageDictionary, PdfDictionary colorSpaceDic){
     PdfNumber wObj = imageDictionary.GetAsNumber(PdfName.WIDTH);
     PdfNumber bpcObj = imageDictionary.GetAsNumber(PdfName.BITSPERCOMPONENT);
     int cpp = GetComponentsPerPixel(imageDictionary.GetAsName(PdfName.COLORSPACE), colorSpaceDic);
     
     int w = wObj.IntValue;
     int bpc = bpcObj != null ? bpcObj.IntValue : 1;
     
     
     int bytesPerRow = (w * bpc * cpp + 7) / 8;
     
     return bytesPerRow;
 }
Exemple #18
0
        public static ComponentCollection ParseDocument(string filename, double conversion)
        {
            ComponentCollection collection = new ComponentCollection();

            collection.scale  = conversion;
            collection.delete = false;

            using (var ms = new System.IO.MemoryStream())
            {
                PdfReader     myPdfReader = new PdfReader(filename);
                PdfDictionary pageDict    = myPdfReader.GetPageN(1);
                PdfArray      annotArray  = pageDict.GetAsArray(PdfName.ANNOTS);



                for (int i = 0; i < annotArray.Size; i++)
                {
                    PdfDictionary curAnnot = annotArray.GetAsDict(i);
                    PdfName       subject  = curAnnot.GetAsName(PdfName.SUBTYPE);
                    if (subject != null)
                    {
                        if (subject == PdfName.CIRCLE)
                        {
                            PdfArray arr = curAnnot.GetAsArray(PdfName.RECT);

                            Point a = new Point(arr[0].ToDouble(), arr[1].ToDouble(), 0);
                            Point b = new Point(arr[0].ToDouble(), arr[1].ToDouble(), 5);

                            Column column = new Column("", "", null, a, b, "", false);
                            collection.Items.Add(column);
                        }

                        else if (subject == PdfName.LINE)
                        {
                            PdfArray arr2 = curAnnot.GetAsArray(PdfName.L);
                            Line     line = new Line()
                            {
                                from = new Point(arr2[0].ToDouble(), arr2[1].ToDouble(), 0),
                                to   = new Point(arr2[2].ToDouble(), arr2[3].ToDouble(), 0)
                            };

                            Wall wall = new Wall("", "", null, line, "", 5, false, false);
                            collection.Items.Add(wall);
                        }

                        else if (subject == PdfName.POLYGON)
                        {
                            PdfArray arr3 = curAnnot.GetAsArray(PdfName.VERTICES);
                            Profile  p    = new Profile();
                            Loop     l    = new Loop()
                            {
                                outline = new List <Component>()
                            };
                            for (int j = 0; j < arr3.Size - 2; j = j + 2)
                            {
                                Point a = new Point(arr3[j].ToDouble(), arr3[j + 1].ToDouble(), 0);
                                Point b = new Point(arr3[j + 2].ToDouble(), arr3[j + 3].ToDouble(), 0);
                                l.outline.Add(new Line()
                                {
                                    from = a, to = b
                                });
                            }
                            p.profile = new List <Loop>()
                            {
                                l
                            };
                            Slab s = new Slab()
                            {
                                surface = p
                            };
                            collection.Items.Add(s);
                        }
                    }
                }
            }

            return(collection);
        }
Exemple #19
0
        /**
         * If the child of a structured element is a dictionary, we inspect the
         * child; we may also draw a tag.
         * 
         * @param k
         *            the child dictionary to inspect
         */
        virtual public void InspectChildDictionary(PdfDictionary k, bool inspectAttributes) {
            if (k == null)
                return;
            PdfName s = k.GetAsName(PdfName.S);
            if (s != null) {
                String tagN = PdfName.DecodeName(s.ToString());
			    String tag = FixTagName(tagN);
                outp.Write("<");
                outp.Write(tag);
                if (inspectAttributes) {
                    PdfDictionary a = k.GetAsDict(PdfName.A);
                    if (a != null) {
                        Dictionary<PdfName, PdfObject>.KeyCollection keys = a.Keys;
                        foreach (PdfName key in keys) {
                            outp.Write(' ');
                            PdfObject value = a.Get(key);
                            value = PdfReader.GetPdfObject(value);
                            outp.Write(XmlName(key));
                            outp.Write("=\"");
                            outp.Write(value.ToString());
                            outp.Write("\"");
                        }
                    }
                }
                outp.Write(">");
                PdfDictionary dict = k.GetAsDict(PdfName.PG);
                if (dict != null)
                    ParseTag(tagN, k.GetDirectObject(PdfName.K), dict);
                InspectChild(k.GetDirectObject(PdfName.K));
                outp.Write("</");
                outp.Write(tag);
                outp.WriteLine(">");
            } else
                InspectChild(k.GetDirectObject(PdfName.K));
        }
Exemple #20
0
        public void OneFile_LinksToTheNextFile_UpdatesLink(string exeFileName)
        {
            HtmlToPdfRunner runner = new HtmlToPdfRunner(exeFileName);

            string htmlFile2Contents = @"
<html>
  <head>
  </head>
  <body>
   Page 2
  </body>
</html>";

            using (TempHtmlFile htmlFile2 = new TempHtmlFile(htmlFile2Contents))
            {
                string htmlFile1Contents = $@"
<html>
  <head>
  </head>
  <body>
   Page 1
   <br/>
   <a href=""{htmlFile2.FilePath}"">Page 2</a>
  </body>
</html>";
                using (TempHtmlFile htmlFile1 = new TempHtmlFile(htmlFile1Contents))
                {
                    using (TempPdfFile pdfFile = new TempPdfFile(this.TestContext))
                    {
                        string             commandLine = $"\"{htmlFile1.FilePath}\" \"{htmlFile2.FilePath}\" \"{pdfFile.FilePath}\"";
                        HtmlToPdfRunResult result      = runner.Run(commandLine);
                        Assert.AreEqual(0, result.ExitCode, result.Output);

                        using (PdfReader pdfReader = new PdfReader(pdfFile.FilePath))
                        {
                            using (PdfDocument pdfDocument = new PdfDocument(pdfReader))
                            {
                                Assert.AreEqual(2, pdfDocument.GetNumberOfPages());

                                // get the first page
                                PdfPage pdfPage = pdfDocument.GetPage(1);

                                // get link annotations
                                List <PdfLinkAnnotation> linkAnnotations = pdfPage.GetAnnotations().OfType <PdfLinkAnnotation>().ToList();
                                Assert.AreEqual(1, linkAnnotations.Count);

                                // get the first link annotation
                                PdfLinkAnnotation linkAnnotation = linkAnnotations.ElementAt(0);
                                Assert.IsNotNull(linkAnnotation);

                                // get action
                                PdfDictionary action = linkAnnotation.GetAction();
                                Assert.IsNotNull(action);

                                // get GoTo sub-type
                                PdfName s = action.GetAsName(PdfName.S);

                                if (exeFileName == HtmlToPdfRunner.HtmlToPdfExe)
                                {
                                    Assert.AreEqual(PdfName.GoTo, s);

                                    // get destination
                                    PdfArray             destination = action.GetAsArray(PdfName.D);
                                    PdfIndirectReference destinationPageReference = destination.GetAsDictionary(0).GetIndirectReference();
                                    PdfName   zoom       = destination.GetAsName(1);
                                    PdfNumber pageOffset = destination.GetAsNumber(2);

                                    // get expected values
                                    PdfPage              pdfPage2              = pdfDocument.GetPage(2);
                                    PdfDictionary        page2Dictionary       = pdfPage2.GetPdfObject();
                                    PdfIndirectReference expectedPageReference = page2Dictionary.GetIndirectReference();
                                    PdfName              expectedZoom          = PdfName.FitH;
                                    float expectedPageOffset = pdfPage2.GetPageSize().GetTop();

                                    // assert
                                    Assert.AreEqual(expectedPageReference, destinationPageReference);
                                    Assert.AreEqual(expectedZoom, zoom);
                                    Assert.AreEqual(expectedPageOffset, pageOffset.FloatValue());
                                }
                                else if (exeFileName == HtmlToPdfRunner.WkhtmltopdfExe)
                                {
                                    Assert.AreEqual(PdfName.URI, s);

                                    PdfString uri = action.GetAsString(PdfName.URI);
                                    Assert.AreEqual(htmlFile2.FilePath, HttpUtility.UrlDecode(uri.ToString()));
                                }
                            }
                        }
                    }
                }
            }
        }