Inheritance: iTextSharp.text.Document
Beispiel #1
1
 /**
  * Use this method to get an instance of the <CODE>PdfWriter</CODE>.
  * @param	document	The <CODE>Document</CODE> that has to be written
  * @param	os	The <CODE>Stream</CODE> the writer has to write to.
  * @param conformanceLevel PDF/A conformance level of a new PDF document
  * @return	a new <CODE>PdfWriter</CODE>
  * @throws	DocumentException on error
  */
 public static PdfAWriter GetInstance(Document document, Stream os, PdfAConformanceLevel conformanceLevel) {
     PdfDocument pdf = new PdfDocument();
     document.AddDocListener(pdf);
     PdfAWriter writer = new PdfAWriter(pdf, os, conformanceLevel);
     pdf.AddWriter(writer);
     return writer;
 }
        /// <summary>
        /// 根据pdf模板写入数据生成新的pdf
        /// </summary>
        /// <param name="saveFile">保存的新pdf路径</param>
        /// <param name="sourceFile">原pdf路径</param>
        public static void AddNewPdf(string saveFile, string sourceFile)
        {
            //写入新的pdf地址
            //sourceFile = @"C:\Users\Administrator\Desktop\ABC\temp.pdf";
            //sourceFile = @"C:\Users\Administrator\Desktop\temp123.pdf";
            iTextSharp.text.pdf.PdfDocument document = new iTextSharp.text.pdf.PdfDocument();
            //读取的源pdf文件
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(sourceFile);
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(saveFile, FileMode.OpenOrCreate));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            pdfStamper.FormFlattening = true;
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            pdfFormFields.AddSubstitutionFont(simheiBase);
            Dictionary <string, string> para = new Dictionary <string, string>();

            para.Add($"Numbering", "12369999995");
            for (int i = 1; i < 38; i++)
            {
                para.Add($"Numbering{i}", "12365");
            }
            foreach (KeyValuePair <string, string> parameter in para)
            {
                pdfStamper.AcroFields.SetField(parameter.Key, parameter.Value);
            }
            //pdfStamper.AcroFields.SetField("Names", "李朝强");
            //pdfStamper.AcroFields.SetField("chk", "yes", true);
            pdfStamper.Close();
            pdfReader.Close();
        }
Beispiel #3
0
        public override void WriteToPdf(PdfDocument doc)
        {
            doc.GetWriter.SetCMYKColorStroke(0, 0, 0, 255);
            doc.GetWriter.SetCMYKColorFill(0, 0, 0, 255);
            doc.GetWriter.BeginText();
            doc.GetWriter.SetTextMatrix(PosX+2, PosY+2);

            while ((customfont.GetWidthPointKerned(Text, FontSize) > Width) || (FontSize == 2)) FontSize--;
            doc.GetWriter.SetFontAndSize(customfont, FontSize);
            doc.GetWriter.ShowText(Text);
            doc.GetWriter.EndText();
            doc.Flush();
        }
        /// <summary>
        /// pdf文件添加图片
        /// </summary>
        /// <param name="oldPath">源PDF文件</param>
        /// <param name="newPath">新PDF文件</param>
        /// <param name="imPath">图片地址</param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public static void AddImg(string oldPath, string newPath, string imPath, float x, float y)
        {
            iTextSharp.text.pdf.PdfDocument doc = new iTextSharp.text.pdf.PdfDocument();


            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(oldPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newPath, FileMode.OpenOrCreate));
            //获取PDF指定页面内容
            var pdfContentByte = pdfStamper.GetOverContent(1);
            //添加图片
            Image image = Image.GetInstance(imPath);

            //设置图片大小
            image.ScaleToFit(100, 100);
            //设置图片位置
            image.SetAbsolutePosition(x, y);
            pdfContentByte.AddImage(image);
            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
            pdfReader.Close();
        }
 // constructors
 /**
  * Constructs a new <CODE>PdfContentByte</CODE>-object.
  *
  * @param wr the writer associated to this content
  */
 public PdfContentByte(PdfWriter wr)
 {
     if (wr != null) {
         writer = wr;
         pdf = writer.PdfDocument;
         autoControlTextBlocks = !pdf.UseSeparateCanvasesForTextAndGraphics;
     }
 }
     // constructors
 
     /**
      * Constructs a new <CODE>PdfContentByte</CODE>-object.
      *
      * @param wr the writer associated to this content
      */
 
     public PdfContentByte(PdfWriter wr) {
         if (wr != null) {
             writer = wr;
             pdf = writer.PdfDocument;
         }
     }
Beispiel #7
0
        /**
         * Constructs a <CODE>PdfAWriter</CODE>.
         * <P>
         * Remark: a PdfAWriter can only be constructed by calling the method <CODE>getInstance(Document document, Stream os, PdfAconformanceLevel conformanceLevel)</CODE>.
         * @param document the <CODE>PdfDocument</CODE> that has to be written
         * @param os the <CODE>Stream</CODE> the writer has to write to
         * @param conformanceLevel PDF/A conformance level of a new PDF document
         */

        protected internal PdfAWriter(PdfDocument document, Stream os, PdfAConformanceLevel conformanceLevel)
            : base(document, os) {
            ((IPdfAConformance) pdfIsoConformance).SetConformanceLevel(conformanceLevel);
            SetPdfVersion(this, conformanceLevel);
        }
Beispiel #8
0
        /**
        * Write out the columns.  After writing, use
        * {@link #isOverflow()} to see if all text was written.
        * @param canvas PdfContentByte to write with
        * @param document document to write to (only used to get page limit info)
        * @param documentY starting y position to begin writing at
        * @return the current height (y position) after writing the columns
        * @throws DocumentException on error
        */
        public float Write(PdfContentByte canvas, PdfDocument document, float documentY)
        {
            this.document = document;
            columnText.Canvas = canvas;
            if (columnDefs.Count == 0) {
                throw new DocumentException(MessageLocalization.GetComposedMessage("multicolumntext.has.no.columns"));
            }
            overflow = false;
            float currentHeight = 0;
            bool done = false;
            while (!done) {
                if (top == AUTOMATIC) {
                    top = document.GetVerticalPosition(true);
                }
                else if (nextY == AUTOMATIC) {
                    nextY = document.GetVerticalPosition(true); // RS - 07/07/2005 - - Get current doc writing position for top of columns on new page.
                }

                ColumnDef currentDef = columnDefs[CurrentColumn];
                columnText.YLine = top;

                float[] left = currentDef.ResolvePositions(Rectangle.LEFT_BORDER);
                float[] right = currentDef.ResolvePositions(Rectangle.RIGHT_BORDER);
                if (document.IsMarginMirroring() && document.PageNumber % 2 == 0){
                    float delta = document.RightMargin - document.Left;
                    left = (float[])left.Clone();
                    right = (float[])right.Clone();
                    for (int i = 0; i < left.Length; i += 2) {
                        left[i] -= delta;
                    }
                    for (int i = 0; i < right.Length; i += 2) {
                        right[i] -= delta;
                    }
                }
                currentHeight = Math.Max(currentHeight, GetHeight(left, right));

                if (currentDef.IsSimple()) {
                    columnText.SetSimpleColumn(left[2], left[3], right[0], right[1]);
                } else {
                    columnText.SetColumns(left, right);
                }

                int result = columnText.Go();
                if ((result & ColumnText.NO_MORE_TEXT) != 0) {
                    done = true;
                    top = columnText.YLine;
                } else if (ShiftCurrentColumn()) {
                    top = nextY;
                } else {  // check if we are done because of height
                    totalHeight += currentHeight;

                    if ((desiredHeight != AUTOMATIC) && (totalHeight >= desiredHeight)) {
                        overflow = true;
                        break;
                    } else {  // need to start new page and reset the columns
                        documentY = nextY;
                        NewPage();
                        currentHeight = 0;
                    }
                }
            }
            if (desiredHeight == AUTOMATIC && columnDefs.Count == 1) {
                currentHeight = documentY - columnText.YLine;
            }
            return currentHeight;
        }
Beispiel #9
0
 /**
 * Constructs a <CODE>PdfWriter</CODE>.
 * <P>
 * Remark: a PdfWriter can only be constructed by calling the method
 * <CODE>getInstance(Document document, Stream os)</CODE>.
 *
 * @param    document    The <CODE>PdfDocument</CODE> that has to be written
 * @param    os          The <CODE>Stream</CODE> the writer has to write to.
 */
 protected PdfWriter(PdfDocument document, Stream os)
     : base(document, os)
 {
     root = new PdfPages(this);
     pdf = document;
     directContent = new PdfContentByte(this);
     directContentUnder = new PdfContentByte(this);
 }
Beispiel #10
0
 public override void Initialize()
 {
     // instantiate document
     pdfDocument = new PdfDocument();
     pdfDocument.Info.Title = title;
     pdfDocument.Info.Author = author;
     // add a page
     PdfPage page = pdfDocument.AddPage();
     page.Orientation = PageOrientation.Portrait;
     // set page size
     page.Width = XUnit.FromMillimeter(bbox.Width);
     page.Height = XUnit.FromMillimeter(bbox.Height);
     // get graphics
     this.pdfGfx = XGraphics.FromPdfPage(page);
     // draw a bounding box
     XRect rect = new XRect(0.5, 0.5, page.Width - 1, page.Height - 1);
     this.pdfGfx.DrawRectangle(XBrushes.White, rect);
     // initialize cotation
     PicCotation._globalCotationProperties._arrowLength = XUnit.FromMillimeter(bbox.Height) / 50.0;
 }
        /// <summary>
        /// 向pdf中添加图片
        /// </summary>
        /// <param name="oldP">源pdf地址</param>
        /// <param name="imP">图片地址</param>
        /// <param name="x">x轴坐标</param>
        /// <param name="y">y轴坐标</param>
        public static void AddImg(string oldP, string newP, string imP, int x, int y)
        {
            string tempFilePath = newP;

            iTextSharp.text.pdf.PdfDocument doc = new iTextSharp.text.pdf.PdfDocument();


            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(oldP);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate));
            //获取PDF指定页面内容
            var pdfContentByte = pdfStamper.GetOverContent(1);
            //添加图片
            Image image = Image.GetInstance(@"C:\Users\Administrator\Desktop\ABC\QRCode.png");

            image.ScaleToFit(60, 60);

            image.SetAbsolutePosition(500, 700);
            pdfContentByte.AddImage(image);
            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
            pdfReader.Close();


            //AcroFields pdfFormFields = pdfStamper.AcroFields;
            //pdfStamper.FormFlattening = true;

            ////BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // //添加图片
            // //Image image = Image.GetInstance(@"C:\Users\Administrator\Desktop\ABC\QRCode.png");
            //image.ScaleToFit(60, 60);
            //pdfStamper.Writer.Add(image);

            ////pdfFormFields.AddSubstitutionFont(simheiBase);
            ////pdfStamper.AcroFields.SetField("Names", "李朝强");
            ////pdfStamper.AcroFields.SetField("chk", "yes", true);
            //pdfStamper.Close();
            //pdfReader.Close();


            ///实例化一个doc 对象
            //Document doc = new Document();
            //try
            //{
            //    ///创建一个pdf 对象
            //    PdfWriter.GetInstance(doc,
            //        new FileStream(@"C:\Users\Administrator\Desktop\ABC\tempimg.pdf", FileMode.Create));
            //    //打开文件
            //    doc.Open();
            //    ///向文件中添加单个图片
            //    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(@"C:\Users\Administrator\Desktop\ABC\QRCode.png");

            //    image.ScaleToFit(60, 60);
            //    doc.Add(image);

            //    ///向文件中循环添加图片


            //}
            //catch (DocumentException dex)
            //{
            //    ////如果文件出现异常输入文件异常

            //}
            //catch (IOException ioex)
            //{
            //    ////如果文件读写出现异常输入文件异常

            //}
            //catch (Exception ex)
            //{

            //}
            //finally
            //{
            //    doc.Close();
            //}
        }
        public static void AddNewPdf()
        {
            string tempFilePath = @"C:\Users\Administrator\Desktop\ABC\temp.pdf";

            iTextSharp.text.pdf.PdfDocument document  = new iTextSharp.text.pdf.PdfDocument();
            iTextSharp.text.pdf.PdfReader   pdfReader = new iTextSharp.text.pdf.PdfReader(@"C:\Users\Administrator\Desktop\temp123.pdf");
            PdfStamper pdfStamper    = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate));
            AcroFields pdfFormFields = pdfStamper.AcroFields;

            pdfStamper.FormFlattening = true;
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            pdfFormFields.AddSubstitutionFont(simheiBase);
            Dictionary <string, string> para = new Dictionary <string, string>();

            para.Add($"Numbering", "12369999995");
            for (int i = 1; i < 38; i++)
            {
                para.Add($"Numbering{i}", "12365");
            }
            foreach (KeyValuePair <string, string> parameter in para)
            {
                pdfStamper.AcroFields.SetField(parameter.Key, parameter.Value);
            }
            //pdfStamper.AcroFields.SetField("Names", "李朝强");
            //pdfStamper.AcroFields.SetField("chk", "yes", true);
            pdfStamper.Close();
            pdfReader.Close();


            ////获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。
            //BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            ////读取模板文件
            //PdfReader reader = new PdfReader(@"C:\Users\Administrator\Desktop\temp123.pdf");

            ////创建文件流用来保存填充模板后的文件
            //MemoryStream stream = new MemoryStream();

            //PdfStamper stamp = new PdfStamper(reader, stream);
            ////设置表单字体,在高版本有用,高版本加入这句话就不会插入字体,低版本无用
            ////stamp.AcroFields.AddSubstitutionFont(baseFont);

            //AcroFields form = stamp.AcroFields;
            ////表单文本框是否锁定
            //stamp.FormFlattening = true;
            //Dictionary<string, string> para = new Dictionary<string, string>();
            //for (int i = 0; i < 38; i++)
            //{
            //    para.Add($"{i}", "tttt");
            //}


            ////填充表单,para为表单的一个(属性-值)字典
            //foreach (KeyValuePair<string, string> parameter in para)
            //{
            //    //要输入中文就要设置域的字体;
            //    form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
            //    //为需要赋值的域设置值;
            //    form.SetField(parameter.Key, parameter.Value);
            //}


            ////最后按顺序关闭io流

            //stamp.Close();
            //reader.Close();
        }
 private PDFFromTemplateHelper( PdfDocument pdfDocument )
 {
     _pdfDocument = pdfDocument;
 }
Beispiel #14
0
 /**
  * @see PdfWriter#getXmpWriter(java.io.MemoryStream, com.itextpdf.text.pdf.PdfDocument.PdfInfo)
  */
 override protected XmpWriter GetXmpWriter(MemoryStream baos, PdfDocument.PdfInfo info)
 {
     if (xmpWriter == null)
         xmpWriter = new PdfAXmpWriter(baos, info, ((IPdfAConformance)pdfIsoConformance).GetConformanceLevel());
     return xmpWriter;
 }
Beispiel #15
0
 /**
 * Constructs a <CODE>PdfWriter</CODE>.
 * <P>
 * Remark: a PdfWriter can only be constructed by calling the method
 * <CODE>getInstance(Document document, Stream os)</CODE>.
 *
 * @param    document    The <CODE>PdfDocument</CODE> that has to be written
 * @param    os          The <CODE>Stream</CODE> the writer has to write to.
 */
 
 protected PdfWriter(PdfDocument document, Stream os) : base(document, os) {
     pdfIsoConformance = GetPdfIsoConformance();
     root = new PdfPages(this);
     pdf = document;
     directContentUnder = new PdfContentByte(this);
     directContent = directContentUnder.Duplicate;
 }
 protected internal virtual XmpWriter GetXmpWriter(MemoryStream baos, PdfDocument.PdfInfo info)
 {
     if (xmpWriter == null)
         xmpWriter = new XmpWriter(baos, info);
     return xmpWriter;
 }
Beispiel #17
0
 /**
 * Use this method to get an instance of the <CODE>PdfWriter</CODE>.
 *
 * @return a new <CODE>PdfWriter</CODE>
 * @param document The <CODE>Document</CODE> that has to be written
 * @param os The <CODE>Stream</CODE> the writer has to write to.
 * @param listener A <CODE>DocListener</CODE> to pass to the PdfDocument.
 * @throws DocumentException on error
 */
 
 public static PdfWriter GetInstance(Document document, Stream os, IDocListener listener)
 {
     PdfDocument pdf = new PdfDocument();
     pdf.AddDocListener(listener);
     document.AddDocListener(pdf);
     PdfWriter writer = new PdfWriter(pdf, os);
     pdf.AddWriter(writer);
     return writer;
 }
Beispiel #18
0
        public override void WriteToPdf(PdfDocument doc)
        {
            //  LABEL
            //  ---------------
            // | Hodnota(Text) |
            //  ---------------

            // biely stvorec obsahujuci hodnotu elementu  (ulozenu v Text)
            // sirka bieleho pola je priamoumerna dlzke textu ktory v nej bude vykresleny
            if (FieldWidth == -1)
                FieldWidth = 15 + (int)customfont.GetWidthPointKerned(Text, FieldFontSize);
            if (FieldHeight == -1)
                FieldHeight = FieldFontSize + 2;
            RectArea r = new RectArea(PosX + 1, PosY +2, FieldWidth+2, FieldHeight);
            r.SetFillColor(0, 0, 0, 0);
            r.AddToDocument(doc);

            if (Label.Text != "")
            {
                // vykreslenie labelu, ktory popisuje hodnoty nizsie
                Label.PosX = this.PosX + 3;
                Label.PosY = this.PosY + FieldHeight + 3;
                Label.WriteToPdf(doc);
            }

            // vpisanie hodnoty elementu do bieleho pola
            Label l = new Label();
            l.Width = FieldWidth-10;
            l.Height = FieldHeight;
            l.Text = this.Text;
            l.PosX = PosX ;
            l.PosY = PosY + 4;
            l.FontSize = FieldFontSize;
            if (FieldWidth > -1)
                l.Width = FieldWidth;
            if (FieldHeight >= -1)
                l.Height = FieldHeight;
            l.WriteToPdf(doc);
        }