Example #1
0
 public virtual void Refresh()
 {
     if (_abs_rectangle == null)
     {
         // quebrar linhas e calcular posição de cada linha de texto
         if (TextLines.Count() > 0)
         {
             (_lines_out, _text_width, _text_height) = PdfFontMetrics.TextCoordinates(
                 width: CalcMaxTextWidth(),
                 lines: TextLines.Select(x => new PdfTextIn(
                                             metrics: x.Font.FontMetrics,
                                             font_name: x.Font.ElementName,
                                             codepage: x.Font.CodePage,
                                             text_scale: x.TextScale,
                                             text: x.TextLine,
                                             h_align: x.HAlign,
                                             color: x.Color,
                                             kerning: x.Font.Kerning)));
         }
         else
         {
             _lines_out   = null;
             _text_width  = 0;
             _text_height = 0;
         }
         // calcular dimensões do box
         _abs_rectangle = CalcRectangle(_text_width, _text_height);
     }
 }
Example #2
0
 // acrescentar linha de texto ao box
 public PdfBox AddLine(PdfTextLine text_line)
 {
     _text_lines.Add(text_line);
     text_line.Initialize(Page);
     _abs_rectangle = null;
     return(this);
 }
 private static void ExtractBBox(PdfRect bbox, JObject node, DataType data_types)
 {
     node.Add("left", bbox.left);
     node.Add("top", bbox.top);
     node.Add("right", bbox.right);
     node.Add("bottom", bbox.bottom);
 }
Example #4
0
        /// <summary>
        /// Convert an absolute position in the same coordinate space as the
        /// given rectangle to a relative position within the bound of the given rectangle
        /// </summary>
        private Point GetRelativePosition(PdfRect rect, Point absPosition)
        {
            var x = (absPosition.X - rect.Left) / (rect.Right - rect.Left);
            var y = (absPosition.Y - rect.Top) / (rect.Bottom - rect.Top);

            return(new Point(x, y));
        }
Example #5
0
 public PdfAngledBox(PdfRect rect, PdfAngle angle, PdfAlign v_align, PdfBorder borders = null, PdfBoxLayout box_layout = null)
     : base(borders, box_layout)
 {
     Rectangle = rect;
     Angle     = angle;
     VAlign    = v_align;
 }
Example #6
0
    public static PdfRect _PdfRect(float Left, float Top, float Right, float Bottom)
    {
        PdfRect freturn = new PdfRect();

        freturn.Left   = Left;
        freturn.Top    = Top;
        freturn.Right  = Right;
        freturn.Bottom = Bottom;
        return(freturn);
    }
        public static void Run(
            String openPath,                            // source PDF document
            String savePath                             // output PDF document
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            PdfPage page = doc.AcquirePage(0);

            if (page == null)
            {
                throw new Exception(pdfix.GetError());
            }

            PdfRect cropBox = page.GetCropBox();

            // place annotation to the middle of the page
            PdfRect annotRect = new PdfRect();

            annotRect.left   = (float)((cropBox.right + cropBox.left) / 2.0) - 10;
            annotRect.bottom = (float)((cropBox.top + cropBox.bottom) / 2.0) - 10;
            annotRect.right  = (float)((cropBox.right + cropBox.left) / 2.0) + 10;
            annotRect.top    = (float)((cropBox.top + cropBox.bottom) / 2.0) + 10;

            PdfTextAnnot annot = (PdfTextAnnot)page.CreateAnnot(PdfAnnotSubtype.kAnnotText, annotRect);

            page.AddAnnot(-1, annot);
            if (annot == null)
            {
                throw new Exception(pdfix.GetError());
            }
            annot.SetAuthor(@"Peter Brown");
            annot.SetContents(@"This is my comment.");
            annot.AddReply(@"Mark Fish", @"This is some reply.");

            page.Release();

            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
        /// <summary>
        /// Get a brush
        /// </summary>
        public GraphicBrush GetBrush(Matrix matrix, PdfRect boundingBox, double alpha, List <FunctionStop> softMask)
        {
            var stops = function.GetBoundaryValues();
            var linearGradientBrush = new GraphicLinearGradientBrush();

            // The whole logic of the shape converter is able to handle both relative and
            // absolute coordinates of gradients. WPF also allows both mapping modes. But
            // there is one single case where absolute coordinates don't work: in a <Path/>
            // object when the stretch mode is other than None. Such a path isn't really
            // helpfull. That's why all parsers generate relative coordinates.

#if GENERATE_RELATIVE_COORDINATES
            var p0 = coords0 * matrix;
            linearGradientBrush.StartPoint = GetRelativePosition(boundingBox, p0);

            var p1 = coords1 * matrix;
            linearGradientBrush.EndPoint = GetRelativePosition(boundingBox, p1);
#else
            linearGradientBrush.MappingMode = BrushMappingMode.Absolute;

            var p0 = coords0 * matrix;
            linearGradientBrush.StartPoint = p0;

            var p1 = coords1 * matrix;
            linearGradientBrush.EndPoint = p1;
#endif

            linearGradientBrush.GradientStops = new List <GraphicGradientStop>();

            for (int i = 0; i < stops.Count; i++)
            {
                var stop = stops[i];

                var graphicGradientStop = new GraphicGradientStop();
                linearGradientBrush.GradientStops.Add(graphicGradientStop);

                var stopAlpha = alpha;

                if (softMask != null)
                {
                    stopAlpha = stopAlpha * softMask[i].Value[0];
                }

                var color = colorSpace.GetColor(stop.Value, stopAlpha);
                graphicGradientStop.Color    = color;
                graphicGradientStop.Position = stop.Stop;
            }

            return(linearGradientBrush);
        }
        //////////////////////////////////////////////////////////////////////////////////////////////////
        // GetParagraphBBox
        // get the text state of the text objects inside paragraph by iterating content kid objects
        //////////////////////////////////////////////////////////////////////////////////////////////////
        private static bool GetStructElementBBox(PdsStructElement struct_elem, ref PdfRect bbox)
        {
            bool result = false;

            for (int i = 0; i < struct_elem.GetNumChildren(); i++)
            {
                if (struct_elem.GetChildType(i) == PdfStructElementType.kPdsStructChildPageContent)
                {
                    // acquire page on which the element is present
                    PdfDoc  doc  = struct_elem.GetStructTree().GetDoc();
                    PdfPage page = doc.AcquirePage(struct_elem.GetChildPageNumber(i));

                    // find text object with mcid on the page to get the text state
                    int mcid    = struct_elem.GetChildMcid(i);
                    var content = page.GetContent();
                    for (int j = 0; j < content.GetNumObjects(); j++)
                    {
                        PdsPageObject page_object = content.GetObject(j);

                        // check if this text page object has the same mcid
                        PdsContentMark content_mark = page_object.GetContentMark();
                        if (content_mark != null && content_mark.GetTagMcid() == mcid)
                        {
                            PdfRect elem_bbox = page_object.GetBBox();
                            if ((bbox.left - bbox.right == 0) || (bbox.top - bbox.bottom == 0))
                            {
                                bbox = elem_bbox;
                            }
                            else
                            {
                                bbox.left   = Math.Min(bbox.left, elem_bbox.left);
                                bbox.right  = Math.Max(bbox.right, elem_bbox.right);
                                bbox.top    = Math.Max(bbox.top, elem_bbox.top);
                                bbox.bottom = Math.Min(bbox.bottom, elem_bbox.bottom);
                            }
                            result = true;
                        }
                    }
                }
                else if (struct_elem.GetChildType(i) == PdfStructElementType.kPdsStructChildElement)
                {
                    PdsObject        kid_obj  = struct_elem.GetChildObject(i);
                    PdsStructElement kid_elem = struct_elem.GetStructTree().GetStructElementFromObject(kid_obj);
                    GetStructElementBBox(kid_elem, ref bbox);
                }
            }
            return(result);
        }
Example #10
0
        /// <summary>
        /// Get a brush
        /// </summary>
        public GraphicBrush GetBrush(Matrix matrix, PdfRect rect, double alpha, List <FunctionStop> softMask)
        {
            var linear = new GraphicLinearGradientBrush();

            linear.StartPoint = new System.Windows.Point(0, 0);
            linear.EndPoint   = new System.Windows.Point(1, 1);

            linear.GradientStops = new List <GraphicGradientStop>();

            var stop = new GraphicGradientStop();

            linear.GradientStops.Add(stop);
            stop.Color    = Colors.Yellow;
            stop.Position = 0;

            stop = new GraphicGradientStop();
            linear.GradientStops.Add(stop);
            stop.Color    = Colors.Salmon;
            stop.Position = 1;

            return(linear);
        }
Example #11
0
        protected override PdfBoundingBox CalcBoundingBox(PdfRect abs_rectangle)
        {
            double llx;
            double lly;

            switch (Angle)
            {
            case PdfAngle.BottomUp:
                llx = abs_rectangle.LowerRight.X;
                lly = Page.Area.Height - abs_rectangle.LowerRight.Y;
                break;

            case PdfAngle.TopDown:
                llx = abs_rectangle.UpperLeft.X;
                lly = Page.Area.Height - abs_rectangle.UpperLeft.Y;
                break;

            default:
                throw new InvalidOperationException();
            }

            return(new PdfBoundingBox(llx, lly, llx + Rectangle.Area.Height, lly + Rectangle.Area.Width));
        }
Example #12
0
        public static void Run(
            String openPath,                            // source PDF document
            String savePath,                            // output PDF document
            String attachmentPath                       // attachment PDF
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // rect for the new annotation
            PdfRect annot_rect = new PdfRect()
            {
                left   = 300,
                right  = 328,
                bottom = 50,
                top    = 118
            };

            // create annotation dictionary and fill it
            PdsDictionary annot_dict  = doc.CreateDictObject(true);
            PdsArray      color_array = annot_dict.PutArray("C");

            color_array.PutNumber(0, 1);
            color_array.PutNumber(1, 0.33f);
            color_array.PutNumber(2, 0.25f);
            annot_dict.PutString("Contents", "AutoTag_Sample_original.pdf");
            annot_dict.PutNumber("F", 28);
            annot_dict.PutString("Name", "Paperclip");
            annot_dict.PutRect("Rect", annot_rect);
            annot_dict.PutString("Subj", "File Attachment");
            annot_dict.PutName("Subtype", "FileAttachment");
            annot_dict.PutString("T", "Mr PDFixer");
            annot_dict.PutName("Type", "Annot");

            PdsDictionary fs_dict = annot_dict.PutDict("FS");

            fs_dict.PutString("F", "AutoTag_Sample_original.pdf");
            fs_dict.PutName("Type", "Filespec");
            fs_dict.PutString("UF", "AutoTag_Sample_original.pdf");

            // open attachment doc
            var fileStm = pdfix.CreateFileStream(attachmentPath, PsFileMode.kPsReadOnly);

            if (fileStm == null)
            {
                throw new Exception(pdfix.GetError());
            }

            byte[] fileData = new byte[fileStm.GetSize()];
            fileStm.Read(0, fileData);

            // create stream object from attachment
            PdsStream filestream = doc.CreateStreamObject(true, null, fileData);

            PdsDictionary ef_dict = fs_dict.PutDict("EF");

            ef_dict.Put("F", filestream);

            // create annotation object from dictionary
            PdfAnnot annot = doc.GetAnnotFromObject(annot_dict);

            // add annotation on the first page
            var page = doc.AcquirePage(0);

            if (page == null)
            {
                throw new Exception(pdfix.GetError());
            }

            if (!page.AddAnnot(0, annot))
            {
                throw new Exception(pdfix.GetError());
            }

            page.Release();

            // save document
            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
Example #13
0
 /// <summary>
 /// Get a brush
 /// </summary>
 public GraphicBrush GetBrush(Matrix parentMatrix, PdfRect rect, double alpha, List <FunctionStop> softMask)
 {
     return(shading.GetBrush(matrix * parentMatrix, rect, alpha, softMask));
 }
Example #14
0
 public PdfJpegImage(byte[] jpeg_data, PdfArea jpeg_area, PdfRect image_position, int bits_per_color = 8)
     : base(jpeg_data, jpeg_area, image_position)
 {
     BitsPerColor = bits_per_color;
 }
        public static void Run(
            String openPath,                            // source PDF document
            String savePath,                            // output PDF document
            String imgPath                              // watermark to apply
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // identify image format from file path
            PdfImageFormat format = PdfImageFormat.kImageFormatJpg;

            if (Path.GetExtension(imgPath).ToLower() == ".png")
            {
                format = PdfImageFormat.kImageFormatPng;
            }

            // load image file data into memory stream
            byte[] bytes  = File.ReadAllBytes(imgPath);
            var    memStm = pdfix.CreateMemStream();

            if (memStm == null)
            {
                throw new Exception(pdfix.GetError());
            }
            memStm.Write(0, bytes);

            // create XObject from the image
            var image_obj = doc.CreateXObjectFromImage(memStm, format);

            if (image_obj == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // find or add annotation on the first page
            var page = doc.AcquirePage(0);

            if (page == null)
            {
                throw new Exception(pdfix.GetError());
            }

            PdfAnnot annot = null;// page.GetAnnot(0);

            if (annot == null)
            {
                // create new annotation
                var page_view = page.AcquirePageView(1, PdfRotate.kRotate0);
                if (page_view == null)
                {
                    throw new Exception(pdfix.GetError());
                }

                // rect for the new annotation
                PdfRect annot_rect = new PdfRect()
                {
                    left   = 100,
                    right  = 300,
                    bottom = 100,
                    top    = 200
                };
                annot = page.CreateAnnot(PdfAnnotSubtype.kAnnotStamp, annot_rect);
                page.AddAnnot(0, annot);
            }

            // set annotation appearance
            if (!annot.SetAppearanceFromXObject(image_obj, PdfAnnotAppearanceMode.kAppearanceNormal))
            {
                throw new Exception(pdfix.GetError());
            }

            page.Release();

            // save document
            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
Example #16
0
        public async Task <ResponseObject> ExtractJsonFromPDF(string email, string licenseKey, string filePath, List <string> imageList)
        {
            ResponseObject responseObject = new ResponseObject();
            List <string>  errorList      = new List <string>();

            try
            {
                Pdfix pdfix = new Pdfix();
                if (pdfix == null)
                {
                    throw new Exception("Pdfix initialization fail");
                }

                if (!pdfix.Authorize(email, licenseKey))
                {
                    throw new Exception(pdfix.GetError());
                }

                PdfDoc doc = pdfix.OpenDoc(filePath, "");
                if (doc == null)
                {
                    throw new Exception();
                }

                int pageCount = doc.GetNumPages();

                List <PDF> pdfList = new List <PDF>();

                for (int i = 0; i < doc.GetNumPages(); i++)
                {
                    List <PDFObject> pdfObjectList = new List <PDFObject>();

                    PdfPage page   = doc.AcquirePage(i);
                    PDF     pdfObj = new PDF();

                    pdfObj.page     = i.ToString();
                    pdfObj.imageUrl = GetBase64String(imageList[i]);
                    _tabOrder       = 0;
                    int annots = page.GetNumAnnots();

                    for (int j = 0; j < page.GetNumAnnots(); j++)
                    {
                        PdfAnnot        pdfAnnot        = page.GetAnnot(j);
                        PdfAnnotSubtype pdfAnnotSubtype = pdfAnnot.GetSubtype();

                        PdfFormField field     = null;
                        bool         isChecked = false;

                        if (pdfAnnotSubtype == PdfAnnotSubtype.kAnnotLink)
                        {
                            var widget = (PdfLinkAnnot)pdfAnnot;
                            field     = doc.GetFormField(j);
                            isChecked = field.GetValue() == field.GetWidgetExportValue(widget);
                        }
                        if (pdfAnnotSubtype == PdfAnnotSubtype.kAnnotWidget)
                        {
                            var widget = (PdfWidgetAnnot)pdfAnnot;
                            field = widget.GetFormField();
                            if (field == null)
                            {
                                field = doc.GetFormField(j);
                            }

                            isChecked = field.GetValue() == field.GetWidgetExportValue(widget);
                        }

                        if (pdfAnnotSubtype == PdfAnnotSubtype.kAnnotHighlight)
                        {
                            var widget = (PdfTextMarkupAnnot)pdfAnnot;
                            field     = doc.GetFormField(j);
                            isChecked = field.GetValue() == field.GetWidgetExportValue(widget);
                        }

                        if (field == null)
                        {
                            field = doc.GetFormField(j);
                            string fieldName = field.GetFullName();
                            errorList.Add(fieldName);
                            throw new Exception();
                        }

                        PDFObject pdfObject = new PDFObject();
                        pdfObject.fieldName   = field.GetFullName();
                        pdfObject.fieldValue  = field.GetValue();
                        pdfObject.maxLength   = field.GetMaxLength();
                        pdfObject.tooltip     = field.GetTooltip();
                        pdfObject.displayName = field.GetDefaultValue();

                        pdfObject.multiLine   = ((field.GetFlags() & Pdfix.kFieldFlagMultiline) != 0) ? true : false;
                        pdfObject.isFormatted = ((field.GetAAction(PdfActionEventType.kActionEventFieldFormat)) != null) ? true : false;
                        pdfObject.required    = ((field.GetFlags() & Pdfix.kFieldFlagRequired) != 0) ? true : false;
                        pdfObject.readOnly    = ((field.GetFlags() & Pdfix.kFieldFlagReadOnly) != 0) ? true : false;
                        pdfObject.tabOrder    = _tabOrder++;
                        pdfObject.isChecked   = isChecked;
                        pdfObject.fieldType   = GetFieldType(field);

                        List <string> dropdownList = new List <string>();
                        for (int k = 0; k < field.GetOptionCount(); k++)
                        {
                            string optionValue = field.GetOptionValue(k);
                            dropdownList.Add(optionValue);
                        }

                        pdfObject.optionList = dropdownList;

                        PdfRect bbox = pdfAnnot.GetBBox();

                        PdfAnnotAppearance pdfAnnotAppearance = pdfAnnot.GetAppearance();
                        PdfPageView        pageView           = page.AcquirePageView(1.0, PdfRotate.kRotate0);
                        if (pageView == null)
                        {
                            throw new Exception(pdfix.GetError());
                        }

                        var devRect = pageView.RectToDevice(bbox);

                        var x      = devRect.left;
                        var y      = devRect.top;
                        var width  = devRect.right - devRect.left;
                        var height = devRect.bottom - devRect.top;

                        var pageWidth  = pageView.GetDeviceWidth();
                        var pageHeight = pageView.GetDeviceHeight();

                        var pdfvalue   = ((double)x / pageWidth) * 100;
                        var percentage = Convert.ToInt32(Math.Round(pdfvalue, 2));

                        pdfObject.x      = ((double)devRect.left / pageView.GetDeviceWidth()) * 100;
                        pdfObject.y      = ((double)devRect.top / pageView.GetDeviceHeight()) * 100;
                        pdfObject.width  = ((double)(devRect.right - devRect.left) / pageView.GetDeviceWidth()) * 100;
                        pdfObject.height = ((double)(devRect.bottom - devRect.top) / pageView.GetDeviceHeight()) * 100;

                        pageView.Release();

                        pdfObjectList.Add(pdfObject);
                    }
                    pdfObj.pdfObjList = pdfObjectList;
                    pdfObj.width      = 927;
                    pdfObj.height     = 1200;
                    pdfList.Add(pdfObj);
                }


                responseObject.flag    = true;
                responseObject.data    = pdfList;
                responseObject.message = "Document Import Successfully";

                doc.Close();
                pdfix.Destroy();
            }
            catch (Exception ex)
            {
                responseObject.errorList = errorList;
                throw ex;
            }

            return(responseObject);
        }
        public static void Run(
            String openPath,                            // source PDF document
            String savePath,                            // output PDF document
            String imgPath                              // watermark to apply
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // identify image format from file path
            PdfImageFormat format = PdfImageFormat.kImageFormatJpg;

            if (Path.GetExtension(imgPath).ToLower() == ".png")
            {
                format = PdfImageFormat.kImageFormatPng;
            }

            // load image file data into memory stream
            byte[] bytes  = File.ReadAllBytes(imgPath);
            var    memStm = pdfix.CreateMemStream();

            if (memStm == null)
            {
                throw new Exception(pdfix.GetError());
            }
            memStm.Write(0, bytes);

            // create XObject from the image
            var image_obj = doc.CreateXObjectFromImage(memStm, format);

            if (image_obj == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // add annotation on the first page
            var page = doc.AcquirePage(0);

            if (page == null)
            {
                throw new Exception(pdfix.GetError());
            }

            var page_view = page.AcquirePageView(1, PdfRotate.kRotate0);

            if (page_view == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // rect for the new annotation
            PdfRect annot_rect = new PdfRect()
            {
                left   = 100,
                right  = 300,
                bottom = 100,
                top    = 200
            };

            PdfAnnot annot = page.CreateAnnot(PdfAnnotSubtype.kAnnotStamp, annot_rect);

            page.AddAnnot(0, annot);
            // create content
            var content = doc.CreateContent();

            // add image to content
            var             xobjdict    = image_obj.GetStreamDict();
            var             width       = xobjdict.GetNumber("Width");
            var             height      = xobjdict.GetNumber("Height");
            var             ratio       = height / width;
            var             res_width   = annot_rect.right - annot_rect.left;
            var             res_height  = res_width * ratio;
            var             center_adj  = ((annot_rect.top - annot_rect.bottom) - res_height) / 2;
            var             imageobject = content.AddNewImage(-1, image_obj, new PdfMatrix(res_width, 0, 0, res_height, 0, center_adj));
            PdfGraphicState imageGs     = new PdfGraphicState();

            imageGs.color_state.fill_opacity = 255;
            imageobject.SetGState(imageGs);

            // create text state
            PdfTextState textState  = new PdfTextState();
            var          colorSpace = doc.CreateColorSpace(PdfColorSpaceFamily.kColorSpaceDeviceRGB);
            var          fontName   = "Segoe UI";
            var          fn         = fontName.Trim();
            var          sysFont    = pdfix.FindSysFont(fn, 0, PdfFontCodepage.kFontDefANSICodepage);

            if (sysFont == null)
            {
                throw new Exception(pdfix.GetError());
            }
            textState.font = doc.CreateFont(sysFont, PdfFontCharset.kFontAnsiCharset, 0);
            sysFont.Destroy();

            if (textState.font == null)
            {
                throw new Exception(pdfix.GetError());
            }

            textState.font_size             = 11;
            textState.color_state.fill_type = PdfFillType.kFillTypeSolid;
            var fill_color = colorSpace.CreateColor();

            fill_color.SetValue(0, 0.5f);
            fill_color.SetValue(1, 0.5f);
            fill_color.SetValue(2, 0.5f);
            textState.color_state.fill_color   = fill_color;
            textState.color_state.fill_opacity = 255;
            textState.color_state.stroke_type  = PdfFillType.kFillTypeSolid;
            var stroke_color = colorSpace.CreateColor();

            stroke_color.SetValue(0, 0);
            stroke_color.SetValue(1, 0);
            stroke_color.SetValue(2, 0);
            textState.color_state.stroke_color   = stroke_color;
            textState.color_state.stroke_opacity = 255;
            textState.char_spacing = 2;

            // add text to content
            var line       = "test text in appearance";
            var textObject = content.AddNewText(-1, textState.font, new PdfMatrix(1, 0, 0, 1, 10, 10));

            if (textObject == null)
            {
                throw new Exception(pdfix.GetError());
            }

            textObject.SetTextState(textState);
            textObject.SetText(line);

            // set annotation appearance
            PdsContentParams contentParams = new PdsContentParams();

            contentParams.bbox      = new PdfRect(annot_rect.right - annot_rect.left, 0, 0, annot_rect.top - annot_rect.bottom);
            contentParams.matrix    = new PdfMatrix(1, 0, 0, 1, 0, 0);
            contentParams.form_type = 1;
            contentParams.flags     = 2;
            var appearance_stream = content.ToObject(doc, contentParams);

            annot.SetAppearanceFromXObject(appearance_stream, PdfAnnotAppearanceMode.kAppearanceNormal);

            page.Release();

            // save document
            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
Example #18
0
 public PdfImage(byte[] image_data, PdfArea image_size, PdfRect image_position)
 {
     ImageData = image_data;
     ImageArea = image_size;
     Rectange  = image_position;
 }
        public static void Run(
            String email,                               // authorization email
            String licenseKey,                          // authorization license key
            String openPath,                            // source PDF document
            String savePath                             // output PDF document
            )
        {
            Pdfix pdfix = new Pdfix();

            if (pdfix == null)
            {
                throw new Exception("Pdfix initialization fail");
            }

            if (!pdfix.Authorize(email, licenseKey))
            {
                throw new Exception(pdfix.GetError());
            }

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            PdfPage page = doc.AcquirePage(0);

            if (page == null)
            {
                throw new Exception(pdfix.GetError());
            }

            PdfRect cropBox = page.GetCropBox();

            // place annotation to the middle of the page
            PdfRect annotRect = new PdfRect();

            annotRect.left   = (cropBox.right + cropBox.left) / 2.0 - 10;
            annotRect.bottom = (cropBox.top + cropBox.bottom) / 2.0 - 10;
            annotRect.right  = (cropBox.right + cropBox.left) / 2.0 + 10;
            annotRect.top    = (cropBox.top + cropBox.bottom) / 2.0 + 10;

            PdfTextAnnot annot = page.AddTextAnnot(-1, annotRect);

            if (annot == null)
            {
                throw new Exception(pdfix.GetError());
            }
            annot.SetAuthor(@"Peter Brown");
            annot.SetContents(@"This is my comment.");
            annot.AddReply(@"Mark Fish", @"This is some reply.");

            page.Release();

            if (!doc.Save(savePath, PdfSaveFlags.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
            pdfix.Destroy();
        }
Example #20
0
 public PdfAutoBox(PdfRect rectangle, PdfAlign v_align, PdfBorder borders = null, PdfBoxLayout box_layout = null)
     : this(rectangle.UpperLeft, PdfGrow.None, v_align, rectangle.Area, null, borders, box_layout)
 {
 }
Example #21
0
 protected override PdfBoundingBox CalcBoundingBox(PdfRect abs_rectangle)
 {
     return(new PdfBoundingBox(abs_rectangle, Page.Area.Height));
 }
Example #22
0
 public static bool contains(PdfRect a, PdfRect b)
 {
     return((a.left <= b.left) && (a.right >= b.right) &&
            (a.bottom <= b.bottom) && (a.top >= b.top));
 }
        public static void Run(
            String openPath,                            // source PDF document
            String savePath                             // dest PDF document
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // cleanup any previous structure tree
            if (!doc.RemoveTags(null, null))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // autotag document first
            if (!doc.AddTags(null, null))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // get the struct tree
            PdsStructTree struct_tree = doc.GetStructTree();

            if (struct_tree == null)
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            PdsStructElement table = GetFirstTable(struct_tree);

            if (table == null)
            {
                throw new Exception("No table found.");
            }

            PdfRect bbox = new PdfRect();

            GetStructElementBBox(table, ref bbox);

            // remove all items from the table to make it untagged cotnent
            for (int i = table.GetNumChildren() - 1; i >= 0; i--)
            {
                table.RemoveChild(i);
            }

            // tag page
            PdfPage page = doc.AcquirePage(0);

            PdePageMap page_map = page.AcquirePageMap();
            PdeElement elem     = page_map.CreateElement(PdfElementType.kPdeImage, null);

            elem.SetBBox(bbox);
            elem.SetAlt("This is image caption");

            // prepare document template to ignore already tagged content
            var doc_prelight = doc.GetTemplate();

            doc_prelight.SetProperty("ignore_tags", 1);

            // re-tag non-tagged page content
            PdePageMap pageMap = page.AcquirePageMap();

            if (pageMap == null)
            {
                throw new Exception(pdfix.GetError());
            }
            if (!pageMap.CreateElements(null, null))
            {
                throw new Exception(pdfix.GetError());
            }

            if (!page_map.AddTags(table, null, null))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // udpate the table element type
            if (!table.SetType("Sect"))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
Example #24
0
 /// <summary>
 /// Get a graphic brush
 /// </summary>
 public GraphicBrush GetBrush(PdfRect boundingBox, List <FunctionStop> softMask)
 {
     return(brushDescriptor.GetBrush(boundingBox, softMask));
 }
Example #25
0
 protected abstract PdfBoundingBox CalcBoundingBox(PdfRect abs_rectangle);
        public static void Run(
            String openPath,                            // source PDF document
            String savePath                             // dest PDF document
            )
        {
            Pdfix pdfix = PdfixEngine.Instance;

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // cleanup any previous structure tree
            if (!doc.RemoveTags(null, null))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // autotag document first
            if (!doc.AddTags(null, null))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // get the struct tree
            PdsStructTree struct_tree = doc.GetStructTree();

            if (struct_tree == null)
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            PdsStructElement paragraph = GetFirstParagraph(struct_tree);

            if (paragraph == null)
            {
                throw new Exception("No paragraph found.");
            }

            PdfRect annot_bbox = new PdfRect();

            GetStructElementBBox(paragraph, ref annot_bbox);

            // add new link annotation to the page
            PdfPage      page  = doc.AcquirePage(0);
            PdfLinkAnnot annot = (PdfLinkAnnot)page.CreateAnnot(PdfAnnotSubtype.kAnnotLink, annot_bbox);

            page.AddAnnot(0, annot);
            if (annot == null)
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // re-tag the document the link annotation
            if (!doc.RemoveTags(null, null))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }
            if (!doc.AddTags(null, null))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            if (!doc.Save(savePath, Pdfix.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
        }
Example #27
0
 public PdfAutoBox(PdfRect rectangle, PdfBoxLayout box_layout = null)
     : this(rectangle.UpperLeft, PdfGrow.None, PdfAlign.Far, rectangle.Area, null, null, box_layout)
 {
 }
Example #28
0
        /// <summary>
        /// Get the color
        /// </summary>
        public GraphicBrush GetBrush(Matrix matrix, PdfRect boundingBox, double alpha, List <FunctionStop> softMask)
        {
            var stops = function.GetBoundaryValues();
            var linearGradientBrush = new GraphicRadialGradientBrush();

            // see comment in LinearGradientShading.cs in GetBrush for more details

#if GENERATE_RELATIVE_COORDINATES
            // calculate the start position relative to the object rectangle
            var center0UserSpace = center0 * matrix;
            linearGradientBrush.StartPoint = GetRelativePosition(boundingBox, center0UserSpace);

            // calculate the end position relative to the object rectangle
            var center1UserSpace = center1 * matrix;
            linearGradientBrush.EndPoint = GetRelativePosition(boundingBox, center1UserSpace);

            // get the center point and a point on the outer ring
            // in user space coordinates
            var centerPointUserSpace = new Point(0, 0) * matrix;
            var outerPointUserSpace  = new Point(1, 1) * matrix;

            // get the radii in user space
            var gradientRadiusXUserSpace = Math.Abs(outerPointUserSpace.X - centerPointUserSpace.X);
            var gradientRadiusYUserSpace = Math.Abs(outerPointUserSpace.Y - centerPointUserSpace.Y);

            // get the object's size in the user space, we need the radii relative to this size
            var objectWidth  = Math.Abs(boundingBox.Right - boundingBox.Left);
            var objectHeight = Math.Abs(boundingBox.Bottom - boundingBox.Top);

            // calculate the relative radius X
            var relativeRadiusX = gradientRadiusXUserSpace / objectWidth;
            linearGradientBrush.RadiusX = radius1 * relativeRadiusX;

            // calculate the relative radius Y
            var relativeRadiusY = gradientRadiusYUserSpace / objectHeight;
            linearGradientBrush.RadiusY = radius1 * relativeRadiusY;
#else
            linearGradientBrush.MappingMode = BrushMappingMode.Absolute;

            // calculate the start position relative to the object rectangle
            var center0UserSpace = center0 * matrix;
            linearGradientBrush.StartPoint = center0UserSpace;

            // calculate the end position relative to the object rectangle
            var center1UserSpace = center1 * matrix;
            linearGradientBrush.EndPoint = center1UserSpace;

            // calculate the radius X
            linearGradientBrush.RadiusX = TransformX(radius1, matrix);

            // calculate the radius Y
            linearGradientBrush.RadiusY = TransformY(radius1, matrix);
#endif

            linearGradientBrush.GradientStops = new List <GraphicGradientStop>();

            if (stops.Count > 0 && !DoubleUtilities.IsZero(stops[0].Stop) && !DoubleUtilities.IsZero(radius0))
            {
                var graphicGradientStop = new GraphicGradientStop();
                linearGradientBrush.GradientStops.Add(graphicGradientStop);

                graphicGradientStop.Color    = Colors.Transparent;
                graphicGradientStop.Position = 0;

                graphicGradientStop = new GraphicGradientStop();
                linearGradientBrush.GradientStops.Add(graphicGradientStop);

                graphicGradientStop.Color    = Colors.Transparent;
                graphicGradientStop.Position = stops[0].Stop;
            }

            for (int i = 0; i < stops.Count; i++)
            {
                var stop = stops[i];

                var graphicGradientStop = new GraphicGradientStop();
                linearGradientBrush.GradientStops.Add(graphicGradientStop);

                var stopAlpha = alpha;

                if (softMask != null)
                {
                    stopAlpha = stopAlpha * softMask[i].Value[0];
                }

                var color = colorSpace.GetColor(stop.Value, stopAlpha);
                graphicGradientStop.Color    = color;
                graphicGradientStop.Position = stop.Stop;
            }

            return(linearGradientBrush);
        }
        public static void Run(
            String email,                               // authorization email
            String licenseKey,                          // authorization license key
            String openPath,                            // source PDF document
            String savePath                             // dest PDF document
            )
        {
            pdfix = new Pdfix();
            if (pdfix == null)
            {
                throw new Exception("Pdfix initialization fail");
            }

            if (!pdfix.Authorize(email, licenseKey))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // cleanup any previous structure tree
            if (!doc.RemoveTags(null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // autotag document first
            if (!doc.AddTags(null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // get the struct tree
            PdsStructTree struct_tree = doc.GetStructTree();

            if (struct_tree == null)
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            PdsStructElement paragraph = GetFirstParagraph(struct_tree);

            if (paragraph == null)
            {
                throw new Exception("No paragraph found.");
            }

            PdfRect annot_bbox = new PdfRect();

            GetStructElementBBox(paragraph, ref annot_bbox);

            // add new link annotation to the page
            PdfPage      page  = doc.AcquirePage(0);
            PdfLinkAnnot annot = page.AddLinkAnnot(0, annot_bbox);

            if (annot == null)
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // re-tag the document the link annotation
            if (!doc.RemoveTags(null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }
            if (!doc.AddTags(null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            if (!doc.Save(savePath, PdfSaveFlags.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
            pdfix.Destroy();
        }
        public static void Run(
            String email,                               // authorization email
            String licenseKey,                          // authorization license key
            String openPath,                            // source PDF document
            String savePath                             // dest PDF document
            )
        {
            pdfix = new Pdfix();
            if (pdfix == null)
            {
                throw new Exception("Pdfix initialization fail");
            }

            if (!pdfix.Authorize(email, licenseKey))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            PdfDoc doc = pdfix.OpenDoc(openPath, "");

            if (doc == null)
            {
                throw new Exception(pdfix.GetError());
            }

            // cleanup any previous structure tree
            if (!doc.RemoveTags(null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // autotag document first
            if (!doc.AddTags(null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // get the struct tree
            PdsStructTree struct_tree = doc.GetStructTree();

            if (struct_tree == null)
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            PdsStructElement table = GetFirstTable(struct_tree);

            if (table == null)
            {
                throw new Exception("No table found.");
            }

            PdfRect bbox = new PdfRect();

            GetStructElementBBox(table, ref bbox);

            // remove all items from the table to make it untagged cotnent
            for (int i = table.GetNumKids() - 1; i >= 0; i--)
            {
                table.RemoveKid(i);
            }

            // tag page
            PdfPage page = doc.AcquirePage(0);

            PdePageMap page_map = page.CreatePageMap();
            PdeElement elem     = page_map.CreateElement(PdfElementType.kPdeImage, null);

            elem.SetBBox(bbox);
            elem.SetAlt("This is image caption");

            // prepare document template to ignore already tagged content
            PdfDocTemplate doc_tmpl = doc.GetDocTemplate();

            doc_tmpl.SetProperty("ignore_tags", 1);

            // re-tag non-tagged page content
            if (!page_map.AcquireElements(null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }
            if (!page_map.AddTags(table, null, IntPtr.Zero))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            // udpate the table element type
            if (!table.SetType("Sect"))
            {
                throw new Exception(pdfix.GetErrorType().ToString());
            }

            if (!doc.Save(savePath, PdfSaveFlags.kSaveFull))
            {
                throw new Exception(pdfix.GetError());
            }

            doc.Close();
            pdfix.Destroy();
        }