An Annotation is a little note that can be added to a page on a document.
Inheritance: IElement
 // ---------------------------------------------------------------------------      
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document(PageSize.A4))
     {
         // step 2
         PdfWriter writer = PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         PdfContentByte canvas = writer.DirectContent;
         // Create a reusable XObject
         PdfTemplate celluloid = canvas.CreateTemplate(595, 84.2f);
         celluloid.Rectangle(8, 8, 579, 68);
         for (float f = 8.25f; f < 581; f += 6.5f)
         {
             celluloid.RoundRectangle(f, 8.5f, 6, 3, 1.5f);
             celluloid.RoundRectangle(f, 72.5f, 6, 3, 1.5f);
         }
         celluloid.SetGrayFill(0.1f);
         celluloid.EoFill();
         writer.ReleaseTemplate(celluloid);
         // Add the XObject ten times
         for (int i = 0; i < 10; i++)
         {
             canvas.AddTemplate(celluloid, 0, i * 84.2f);
         }
         // Add the movie posters
         Image img;
         Annotation annotation;
         float x = 11.5f;
         float y = 769.7f;
         string RESOURCE = Utility.ResourcePosters;
         foreach (Movie movie in PojoFactory.GetMovies())
         {
             img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"));
             img.ScaleToFit(1000, 60);
             img.SetAbsolutePosition(x + (45 - img.ScaledWidth) / 2, y);
             annotation = new Annotation(
               0, 0, 0, 0,
               string.Format(IMDB, movie.Imdb)
             );
             img.Annotation = annotation;
             canvas.AddImage(img);
             x += 48;
             if (x > 578)
             {
                 x = 11.5f;
                 y -= 84.2f;
             }
         }
     }
 }
        /**
        * Adds an <CODE>Image</CODE> to the page. The positioning of the <CODE>Image</CODE>
        * is done with the transformation matrix. To position an <CODE>image</CODE> at (x,y)
        * use AddImage(image, image_width, 0, 0, image_height, x, y). The image can be placed inline.
        * @param image the <CODE>Image</CODE> object
        * @param a an element of the transformation matrix
        * @param b an element of the transformation matrix
        * @param c an element of the transformation matrix
        * @param d an element of the transformation matrix
        * @param e an element of the transformation matrix
        * @param f an element of the transformation matrix
        * @param inlineImage <CODE>true</CODE> to place this image inline, <CODE>false</CODE> otherwise
        * @throws DocumentException on error
        */
        public virtual void AddImage(Image image, float a, float b, float c, float d, float e, float f, bool inlineImage)
        {
            if (image.Layer != null)
                BeginLayer(image.Layer);
            if (image.IsImgTemplate()) {
                writer.AddDirectImageSimple(image);
                PdfTemplate template = image.TemplateData;
                float w = template.Width;
                float h = template.Height;
                AddTemplate(template, a / w, b / w, c / h, d / h, e, f);
            }
            else {
                if (inText && autoControlTextBlocks) {
                    EndText();
                }
                if (writer.IsTagged() && allowTaggedImages)
                    BeginMarkedContentSequence(new PdfStructureElement(GetParentStructureElement(), PdfName.FIGURE));
                content.Append("q ");
                content.Append(a).Append(' ');
                content.Append(b).Append(' ');
                content.Append(c).Append(' ');
                content.Append(d).Append(' ');
                content.Append(e).Append(' ');
                content.Append(f).Append(" cm");
                if (inlineImage) {
                    content.Append("\nBI\n");
                    PdfImage pimage = new PdfImage(image, "", null);
                    if (image is ImgJBIG2) {
                        byte[] globals = ((ImgJBIG2)image).GlobalBytes;
                        if (globals != null) {
                            PdfDictionary decodeparms = new PdfDictionary();
                            decodeparms.Put(PdfName.JBIG2GLOBALS, writer.GetReferenceJBIG2Globals(globals));
                            pimage.Put(PdfName.DECODEPARMS, decodeparms);
                        }
                    }
                    foreach (PdfName key in pimage.Keys) {
                        if (!abrev.ContainsKey(key))
                            continue;
                        PdfObject value = pimage.Get(key);
                        String s = abrev[key];
                        content.Append(s);
                        bool check = true;
                        if (key.Equals(PdfName.COLORSPACE) && value.IsArray()) {
                            PdfArray ar = (PdfArray)value;
                            if (ar.Size == 4
                                && PdfName.INDEXED.Equals(ar.GetAsName(0))
                                && ar[1].IsName()
                                && ar[2].IsNumber()
                                && ar[3].IsString()
                            ) {
                                check = false;
                            }

                        }
                        if (check && key.Equals(PdfName.COLORSPACE) && !value.IsName()) {
                            PdfName cs = writer.GetColorspaceName();
                            PageResources prs = PageResources;
                            prs.AddColor(cs, writer.AddToBody(value).IndirectReference);
                            value = cs;
                        }
                        value.ToPdf(null, content);
                        content.Append('\n');
                    }
                    content.Append("ID\n");
                    pimage.WriteContent(content);
                    content.Append("\nEI\nQ").Append_i(separator);
                }
                else {
                    PdfName name;
                    PageResources prs = PageResources;
                    Image maskImage = image.ImageMask;
                    if (maskImage != null) {
                        name = writer.AddDirectImageSimple(maskImage);
                        prs.AddXObject(name, writer.GetImageReference(name));
                    }
                    name = writer.AddDirectImageSimple(image);
                    name = prs.AddXObject(name, writer.GetImageReference(name));
                    content.Append(' ').Append(name.GetBytes()).Append(" Do Q").Append_i(separator);
                }
                if (writer.IsTagged() && allowTaggedImages)
                    EndMarkedContentSequence();
            }
            if (image.HasBorders()) {
                SaveState();
                float w = image.Width;
                float h = image.Height;
                ConcatCTM(a / w, b / w, c / h, d / h, e, f);
                Rectangle(image);
                RestoreState();
            }
            if (image.Layer != null)
                EndLayer();
            Annotation annot = image.Annotation;
            if (annot == null)
                return;
            float[] r = new float[unitRect.Length];
            for (int k = 0; k < unitRect.Length; k += 2) {
                r[k] = a * unitRect[k] + c * unitRect[k + 1] + e;
                r[k + 1] = b * unitRect[k] + d * unitRect[k + 1] + f;
            }
            float llx = r[0];
            float lly = r[1];
            float urx = llx;
            float ury = lly;
            for (int k = 2; k < r.Length; k += 2) {
                llx = Math.Min(llx, r[k]);
                lly = Math.Min(lly, r[k + 1]);
                urx = Math.Max(urx, r[k]);
                ury = Math.Max(ury, r[k + 1]);
            }
            annot = new Annotation(annot);
            annot.SetDimensions(llx, lly, urx, ury);
            PdfAnnotation an = PdfAnnotationsImp.ConvertAnnotation(writer, annot, new Rectangle(llx, lly, urx, ury));
            if (an == null)
                return;
            AddAnnotation(an);
        }
Example #3
0
 public Annotation(Annotation an) {
     annotationtype = an.annotationtype;
     annotationAttributes = an.annotationAttributes;
     llx = an.llx;
     lly = an.lly;
     urx = an.urx;
     ury = an.ury;
 }
Example #4
0
        /// <summary>
        /// Constructs an Image object duplicate.
        /// </summary>
        /// <param name="image">another Image object.</param>
        public Image(Image image) : base(image) {
            this.type = image.type;
            this.url = image.url;
            this.rawData = image.rawData;
            this.bpc = image.bpc;
            this.template = image.template;
            this.alignment = image.alignment;
            this.alt = image.alt;
            this.absoluteX = image.absoluteX;
            this.absoluteY = image.absoluteY;
            this.plainWidth = image.plainWidth;
            this.plainHeight = image.plainHeight;
            this.scaledWidth = image.scaledWidth;
            this.scaledHeight = image.scaledHeight;
            this.mySerialId = image.mySerialId;

            this.directReference = image.directReference;

            this.rotationRadians = image.rotationRadians;
            this.initialRotation = image.initialRotation;
            this.indentationLeft = image.indentationLeft;
            this.indentationRight = image.indentationRight;
            this.spacingBefore = image.spacingBefore;
            this.spacingAfter = image.spacingAfter;

            this.widthPercentage = image.widthPercentage;
            this.scaleToFitLineWhenOverflow = image.scaleToFitLineWhenOverflow;
            this.scaleToFitHeight = image.scaleToFitHeight;
            this.annotation = image.annotation;
            this.layer = image.layer;
            this.interpolation = image.interpolation;
            this.originalType = image.originalType;
            this.originalData = image.originalData;
            this.deflated = image.deflated;
            this.dpiX = image.dpiX;
            this.dpiY = image.dpiY;
            this.XYRatio = image.XYRatio;

            this.colorspace = image.colorspace;
            this.invert = image.invert;
            this.profile = image.profile;
            this.additional = image.additional;
            this.mask = image.mask;
            this.imageMask = image.imageMask;
            this.smask = image.smask;
            this.transparency = image.transparency;
            this.role = image.role;
            if (image.accessibleAttributes != null)
                this.accessibleAttributes = new Dictionary<PdfName, PdfObject>(image.accessibleAttributes);
            ID = image.ID;
        }
 /**
 * Constructs a RtfAnnotation based on an Annotation.
 * 
 * @param doc The RtfDocument this RtfAnnotation belongs to
 * @param annotation The Annotation this RtfAnnotation is based off
 */
 public RtfAnnotation(RtfDocument doc, Annotation annotation) : base(doc) {
     title = annotation.Title;
     content = annotation.Content;
 }
 /// <summary>
 /// Constructs an Image object duplicate.
 /// </summary>
 /// <param name="image">another Image object.</param>
 public Image(Image image)
     : base(image)
 {
     this.type = image.type;
     this.url = image.url;
     this.alignment = image.alignment;
     this.alt = image.alt;
     this.absoluteX = image.absoluteX;
     this.absoluteY = image.absoluteY;
     this.plainWidth = image.plainWidth;
     this.plainHeight = image.plainHeight;
     this.scaledWidth = image.scaledWidth;
     this.scaledHeight = image.scaledHeight;
     this.rotationRadians = image.rotationRadians;
     this.indentationLeft = image.indentationLeft;
     this.indentationRight = image.indentationRight;
     this.colorspace = image.colorspace;
     this.rawData = image.rawData;
     this.template = image.template;
     this.bpc = image.bpc;
     this.transparency = image.transparency;
     this.mySerialId = image.mySerialId;
     this.invert = image.invert;
     this.dpiX = image.dpiX;
     this.dpiY = image.dpiY;
     this.mask = image.mask;
     this.imageMask = image.imageMask;
     this.interpolation = image.interpolation;
     this.annotation = image.annotation;
     this.profile = image.profile;
     this.deflated = image.deflated;
     this.additional = image.additional;
     this.smask = image.smask;
     this.XYRatio = image.XYRatio;
     this.originalData = image.originalData;
     this.originalType = image.originalType;
     this.spacingAfter = image.spacingAfter;
     this.spacingBefore = image.spacingBefore;
     this.widthPercentage = image.widthPercentage;
     this.layer = image.layer;
     this.initialRotation = image.initialRotation;
     this.directReference = image.directReference;
 }
Example #7
0
 public static PdfAnnotation ConvertAnnotation(PdfWriter writer, Annotation annot, Rectangle defaultRect) {
     switch (annot.AnnotationType) {
         case Annotation.URL_NET:
             return new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((Uri) annot.Attributes[Annotation.URL]));
         case Annotation.URL_AS_STRING:
             return new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String) annot.Attributes[Annotation.FILE]));
         case Annotation.FILE_DEST:
             return new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String) annot.Attributes[Annotation.FILE], (String) annot.Attributes[Annotation.DESTINATION]));
         case Annotation.SCREEN:
             bool[] sparams = (bool[])annot.Attributes[Annotation.PARAMETERS];
             String fname = (String) annot.Attributes[Annotation.FILE];
             String mimetype = (String) annot.Attributes[Annotation.MIMETYPE];
             PdfFileSpecification fs;
             if (sparams[0])
                 fs = PdfFileSpecification.FileEmbedded(writer, fname, fname, null);
             else
                 fs = PdfFileSpecification.FileExtern(writer, fname);
             PdfAnnotation ann = PdfAnnotation.CreateScreen(writer, new Rectangle(annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry()),
                     fname, fs, mimetype, sparams[1]);
             return ann;
         case Annotation.FILE_PAGE:
             return new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String) annot.Attributes[Annotation.FILE], (int)annot.Attributes[Annotation.PAGE]));
         case Annotation.NAMED_DEST:
             return new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((int) annot.Attributes[Annotation.NAMED]));
         case Annotation.LAUNCH:
             return new PdfAnnotation(writer, annot.GetLlx(), annot.GetLly(), annot.GetUrx(), annot.GetUry(), new PdfAction((String) annot.Attributes[Annotation.APPLICATION],(String) annot.Attributes[Annotation.PARAMETERS],(String) annot.Attributes[Annotation.OPERATION],(String) annot.Attributes[Annotation.DEFAULTDIR]));
         default:
             return new PdfAnnotation(writer, defaultRect.Left, defaultRect.Bottom, defaultRect.Right, defaultRect.Top, new PdfString(annot.Title, PdfObject.TEXT_UNICODE), new PdfString(annot.Content, PdfObject.TEXT_UNICODE));
     }
 }
Example #8
0
        /// <summary>
        /// This method deals with the starting tags.
        /// </summary>
        /// <param name="name">the name of the tag</param>
        /// <param name="attributes">the list of attributes</param>
        public void HandleStartingTags(String name, Properties attributes)
        {
            //System.err.Println("Start: " + name);
            if (ignore || ElementTags.IGNORE.Equals(name)) {
                ignore = true;
                return;
            }

            // maybe there is some meaningful data that wasn't between tags
            if (currentChunk != null) {
                ITextElementArray current;
                try {
                    current = (ITextElementArray) stack.Pop();
                }
                catch {
                    if (bf == null) {
                        current = new Paragraph("", new Font());
                    }
                    else {
                        current = new Paragraph("", new Font(this.bf));
                    }
                }
                current.Add(currentChunk);
                stack.Push(current);
                currentChunk = null;
            }

            // registerfont
            if (name.Equals("registerfont")) {
                FontFactory.Register(attributes);
            }

            // header
            if (ElementTags.HEADER.Equals(name)) {
                stack.Push(new HeaderFooter(attributes));
                return;
            }

            // footer
            if (ElementTags.FOOTER.Equals(name)) {
                stack.Push(new HeaderFooter(attributes));
                return;
            }

            // before
            if (name.Equals("before")) {
                HeaderFooter tmp = (HeaderFooter)stack.Pop();

                tmp.Before = new Phrase(attributes);
                stack.Push(tmp);
                return;
            }

            // after
            if (name.Equals("after")) {
                HeaderFooter tmp = (HeaderFooter)stack.Pop();

                tmp.After = new Phrase(attributes);
                stack.Push(tmp);
                return;
            }

            // chunks
            if (Chunk.IsTag(name)) {
                currentChunk = new Chunk(attributes);
                if (bf != null) {
                    currentChunk.Font = new Font(this.bf);
                }
                return;
            }

            // symbols
            if (EntitiesToSymbol.IsTag(name)) {
                Font f = new Font();
                if (currentChunk != null) {
                    HandleEndingTags(ElementTags.CHUNK);
                    f = currentChunk.Font;
                }
                currentChunk = EntitiesToSymbol.Get(attributes[ElementTags.ID], f);
                return;
            }

            // phrases
            if (Phrase.IsTag(name)) {
                stack.Push(new Phrase(attributes));
                return;
            }

            // anchors
            if (Anchor.IsTag(name)) {
                stack.Push(new Anchor(attributes));
                return;
            }

            // paragraphs and titles
            if (Paragraph.IsTag(name) || Section.IsTitle(name)) {
                stack.Push(new Paragraph(attributes));
                return;
            }

            // lists
            if (List.IsTag(name)) {
                stack.Push(new List(attributes));
                return;
            }

            // listitems
            if (ListItem.IsTag(name)) {
                stack.Push(new ListItem(attributes));
                return;
            }

            // cells
            if (Cell.IsTag(name)) {
                stack.Push(new Cell(attributes));
                return;
            }

            // tables
            if (Table.IsTag(name)) {
                Table table = new Table(attributes);
                float[] widths = table.ProportionalWidths;
                for (int i = 0; i < widths.Length; i++) {
                    if (widths[i] == 0) {
                        widths[i] = 100.0f / (float)widths.Length;
                    }
                }
                try {
                    table.Widths = widths;
                }
                catch (BadElementException bee) {
                    // this shouldn't happen
                    throw new Exception("", bee);
                }
                stack.Push(table);
                return;
            }

            // sections
            if (Section.IsTag(name)) {
                IElement previous = (IElement) stack.Pop();
                Section section;
                section = ((Section)previous).AddSection(attributes);
                stack.Push(previous);
                stack.Push(section);
                return;
            }

            // chapters
            if (Chapter.IsTag(name)) {
                String value; // changed after a suggestion by Serge S. Vasiljev
                if ((value = (String)attributes.Remove(ElementTags.NUMBER)) != null){
                    chapters = int.Parse(value);
                }
                else {
                    chapters++;
                }
                Chapter chapter = new Chapter(attributes,chapters);
                stack.Push(chapter);
                return;
            }

            // images
            if (Image.IsTag(name)) {
                try {
                    Image img = Image.GetInstance(attributes);
                    Object current;
                    try {
                        // if there is an element on the stack...
                        current = stack.Pop();
                        // ...and it's a Chapter or a Section, the Image can be added directly
                        if (current is Chapter || current is Section || current is Cell) {
                            ((ITextElementArray)current).Add(img);
                            stack.Push(current);
                            return;
                        }
                            // ...if not, the Image is wrapped in a Chunk before it's added
                        else {
                            Stack newStack = new Stack();
                            try {
                                while (! (current is Chapter || current is Section || current is Cell)) {
                                    newStack.Push(current);
                                    if (current is Anchor) {
                                        img.Annotation = new Annotation(0, 0, 0, 0, ((Anchor)current).Reference);
                                    }
                                    current = stack.Pop();
                                }
                                ((ITextElementArray)current).Add(img);
                                stack.Push(current);
                            }
                            catch {
                                document.Add(img);
                            }
                            while (!(newStack.Count == 0)) {
                                stack.Push(newStack.Pop());
                            }
                            return;
                        }
                    }
                    catch {
                        // if there is no element on the stack, the Image is added to the document
                        try {
                            document.Add(img);
                        }
                        catch (DocumentException de) {
                            throw new Exception("", de);
                        }
                        return;
                    }
                }
                catch (Exception e) {
                    throw new Exception("", e);
                }
            }

            // annotations
            if (Annotation.IsTag(name)) {
                Annotation annotation = new Annotation(attributes);
                ITextElementArray current;
                try {
                    try {
                        current = (ITextElementArray) stack.Pop();
                        try {
                            current.Add(annotation);
                        }
                        catch {
                            document.Add(annotation);
                        }
                        stack.Push(current);
                    }
                    catch {
                        document.Add(annotation);
                    }
                    return;
                }
                catch (DocumentException de) {
                    throw new Exception("", de);
                }
            }

            // newlines
            if (IsNewline(name)) {
                ITextElementArray current;
                try {
                    current = (ITextElementArray) stack.Pop();
                    current.Add(Chunk.NEWLINE);
                    stack.Push(current);
                }
                catch {
                    if (currentChunk == null) {
                        try {
                            document.Add(Chunk.NEWLINE);
                        }
                        catch (DocumentException de) {
                            throw new Exception("", de);
                        }
                    }
                    else {
                        currentChunk.Append("\n");
                    }
                }
                return;
            }

            // newpage
            if (IsNewpage(name)) {
                ITextElementArray current;
                try {
                    current = (ITextElementArray) stack.Pop();
                    Chunk newPage = new Chunk("");
                    newPage.SetNewPage();
                    if (bf != null) {
                        newPage.Font = new Font(this.bf);
                    }
                    current.Add(newPage);
                    stack.Push(current);
                }
                catch {
                    document.NewPage();
                }
                return;
            }

            // documentroot
            if (IsDocumentRoot(name)) {
                String value;
                // pagesize and orientation specific code suggested by Samuel Gabriel
                // Updated by Ricardo Coutinho. Only use if set in html!
                Rectangle pageSize = null;
                String orientation = null;
                foreach (string key in attributes.Keys) {
                    value = attributes[key];
                    // margin specific code suggested by Reza Nasiri
                    if (Util.EqualsIgnoreCase(ElementTags.LEFT, key))
                        leftMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo);
                    if (Util.EqualsIgnoreCase(ElementTags.RIGHT, key))
                        rightMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo);
                    if (Util.EqualsIgnoreCase(ElementTags.TOP, key))
                        topMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo);
                    if (Util.EqualsIgnoreCase(ElementTags.BOTTOM, key))
                        bottomMargin = float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo);
                    if (ElementTags.PAGE_SIZE.Equals(key)) {
                        pageSize = (Rectangle)typeof(PageSize).GetField(value).GetValue(null);
                    } else if (ElementTags.ORIENTATION.Equals(key)) {
                        if ("landscape".Equals(value)) {
                            orientation = "landscape";
                        }
                    } else {
                        document.Add(new Meta(key, value));
                    }
                }
                if(pageSize != null) {
                    if ("landscape".Equals(orientation)) {
                        pageSize = pageSize.Rotate();
                    }
                    document.SetPageSize(pageSize);
                }
                document.SetMargins(leftMargin, rightMargin, topMargin,
                        bottomMargin);
                if (controlOpenClose)
                    document.Open();
            }
        }
Example #9
0
        public static void Genera(string sourcePath,string content)
        {
            sourcePath = HttpContext.Current.Server.MapPath(sourcePath);
            //定义一个Document,并设置页面大小为A4,竖向
            iTextSharp.text.Document doc = new Document(PageSize.A4);
            try
            {
                //写实例
                PdfWriter.GetInstance(doc, new FileStream(sourcePath, FileMode.Create));
                //打开document
                doc.Open();

                //载入字体
                BaseFont baseFont = BaseFont.CreateFont(
                    "C:\\WINDOWS\\FONTS\\SIMHEI.TTF", //黑体
                    BaseFont.IDENTITY_H, //横向字体
                    BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 9);

                //写入一个段落, Paragraph
                doc.Add(new Paragraph("第一段:" + content, font));
                doc.Add(new Paragraph("这是第二段 !", font));

                #region 图片
                //以下代码用来添加图片,此时图片是做为背景加入到pdf文件当中的:

                Stream inputImageStream = new FileStream(HttpContext.Current.Server.MapPath("~/images/logo.jpg"), FileMode.Open, FileAccess.Read, FileShare.Read);
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                image.SetAbsolutePosition(0, 0);
                image.Alignment = iTextSharp.text.Image.UNDERLYING;    //这里可以设定图片是做为背景还是做为元素添加到文件中
                doc.Add(image);

                #endregion
                #region 其他元素
                doc.Add(new Paragraph("Hello World"));
                //另起一行。有几种办法建立一个段落,如:
                Paragraph p1 = new Paragraph(new Chunk("This is my first paragraph.\n", FontFactory.GetFont(FontFactory.HELVETICA, 12)));
                Paragraph p2 = new Paragraph(new Phrase("This is my second paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12)));
                Paragraph p3 = new Paragraph("This is my third paragraph.", FontFactory.GetFont(FontFactory.HELVETICA, 12));
                //所有有些对象将被添加到段落中:
                p1.Add("you can add string here\n\t");
                p1.Add(new Chunk("you can add chunks \n")); p1.Add(new Phrase("or you can add phrases.\n"));
                doc.Add(p1); doc.Add(p2); doc.Add(p3);

                //创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块:
                Chunk chunk = new Chunk("创建了一个内容为“hello World”、红色、斜体、COURIER字体、尺寸20的一个块", FontFactory.GetFont(FontFactory.COURIER, 20, iTextSharp.text.Font.COURIER, new iTextSharp.text.Color(255, 0, 0)));
                doc.Add(chunk);
                //如果你希望一些块有下划线或删除线,你可以通过改变字体风格简单做到:
                Chunk chunk1 = new Chunk("This text is underlined", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED));
                Chunk chunk2 = new Chunk("This font is of type ITALIC | STRIKETHRU", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.STRIKETHRU));
                //改变块的背景
                chunk2.SetBackground(new iTextSharp.text.Color(0xFF, 0xFF, 0x00));
                //上标/下标
                chunk1.SetTextRise(5);
                doc.Add(chunk1);
                doc.Add(chunk2);

                //外部链接示例:
                Anchor anchor = new Anchor("website", FontFactory.GetFont(FontFactory.HELVETICA, 12, iTextSharp.text.Font.UNDEFINED, new iTextSharp.text.Color(0, 0, 255)));
                anchor.Reference = "http://itextsharp.sourceforge.net";
                anchor.Name = "website";
                //内部链接示例:
                Anchor anchor1 = new Anchor("This is an internal link\n\n");
                anchor1.Name = "link1";
                Anchor anchor2 = new Anchor("Click here to jump to the internal link\n\f");
                anchor2.Reference = "#link1";
                doc.Add(anchor); doc.Add(anchor1); doc.Add(anchor2);

                //排序列表示例:
                List list = new List(true, 20);
                list.Add(new ListItem("First line"));
                list.Add(new ListItem("The second line is longer to see what happens once the end of the line is reached. Will it start on a new line?"));
                list.Add(new ListItem("Third line"));
                doc.Add(list);

                //文本注释:
                Annotation a = new Annotation("authors", "Maybe its because I wanted to be an author myself that I wrote iText.");
                doc.Add(a);

                //包含页码没有任何边框的页脚。
                iTextSharp.text.HeaderFooter footer = new iTextSharp.text.HeaderFooter(new Phrase("This is page: "), true);
                footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
                doc.Footer = footer;

                //Chapter对象和Section对象自动构建一个树:
                iTextSharp.text.Font f1 = new iTextSharp.text.Font();
                f1.SetStyle(iTextSharp.text.Font.BOLD);
                Paragraph cTitle = new Paragraph("This is chapter 1", f1);
                Chapter chapter = new Chapter(cTitle, 1);
                Paragraph sTitle = new Paragraph("This is section 1 in chapter 1", f1);
                Section section = chapter.AddSection(sTitle, 1);
                doc.Add(chapter);

                //构建了一个简单的表:
                Table aTable = new Table(4, 4);
                aTable.AutoFillEmptyCells = true;
                aTable.AddCell("2.2", new System.Drawing.Point(2, 2));
                aTable.AddCell("3.3", new System.Drawing.Point(3, 3));
                aTable.AddCell("2.1", new System.Drawing.Point(2, 1));
                aTable.AddCell("1.3", new System.Drawing.Point(1, 3));
                doc.Add(aTable);
                //构建了一个不简单的表:
                Table table = new Table(3);
                table.BorderWidth = 1;
                table.BorderColor = new iTextSharp.text.Color(0, 0, 255);
                table.Cellpadding = 5;
                table.Cellspacing = 5;
                Cell cell = new Cell("header");
                cell.Header = true;
                cell.Colspan = 3;
                table.AddCell(cell);
                cell = new Cell("example cell with colspan 1 and rowspan 2");
                cell.Rowspan = 2;
                cell.BorderColor = new iTextSharp.text.Color(255, 0, 0);
                table.AddCell(cell);
                table.AddCell("1.1");
                table.AddCell("2.1");
                table.AddCell("1.2");
                table.AddCell("2.2");
                table.AddCell("cell test1");
                cell = new Cell("big cell");
                cell.Rowspan = 2;
                cell.Colspan = 2;
                cell.BackgroundColor = new iTextSharp.text.Color(0xC0, 0xC0, 0xC0);
                table.AddCell(cell);
                table.AddCell("cell test2");
                // 改变了单元格“big cell”的对齐方式:
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                doc.Add(table);

                #endregion
                //关闭document
                doc.Close();
                //打开PDF,看效果
                //Process.Start(sourcePath);
            }
            catch (DocumentException de)
            {
                Console.WriteLine(de.Message);
                Console.ReadKey();
            }
            catch (IOException io)
            {
                Console.WriteLine(io.Message);
                Console.ReadKey();
            }
        }
Example #10
0
 /**
 * Write an <code>Annotation</code>
 *
 * @param annotationElement The <code>Annotation</code> to be written
 * @param outp The <code>MemoryStream</code> to write to
 *
 * @throws IOException
 */
 private void WriteAnnotation(Annotation annotationElement, MemoryStream outp)
 {
     int id = GetRandomInt();
     outp.WriteByte(openGroup);
     outp.Write(extendedEscape, 0, extendedEscape.Length);
     outp.Write(annotationID, 0, annotationID.Length);
     outp.WriteByte(delimiter);
     WriteInt(outp, id);
     outp.WriteByte(closeGroup);
     outp.WriteByte(openGroup);
     outp.Write(extendedEscape, 0, extendedEscape.Length);
     outp.Write(annotationAuthor, 0, annotationAuthor.Length);
     outp.WriteByte(delimiter);
     byte[] t = DocWriter.GetISOBytes(annotationElement.Title);
     outp.Write(t, 0, t.Length);
     outp.WriteByte(closeGroup);
     outp.WriteByte(openGroup);
     outp.Write(extendedEscape, 0, extendedEscape.Length);
     outp.Write(annotation, 0, annotation.Length);
     outp.WriteByte(escape);
     outp.Write(paragraphDefaults, 0, paragraphDefaults.Length);
     outp.WriteByte(delimiter);
     t = DocWriter.GetISOBytes(annotationElement.Content);
     outp.Write(t, 0, t.Length);
     outp.WriteByte(closeGroup);
 }