如何在绝对位置插入iTextsharp.text.rectangle矩形? [英] How to insert a iTextsharp.text.rectangle rectangle at an absolute position?

查看:701
本文介绍了如何在绝对位置插入iTextsharp.text.rectangle矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码(也发布在http://stackoverflow.com/questions/38568690/how-to-insert-a-itextsharp-text-rectangle-rectangle-at-an-absolute-position),,br />

Using the code below (also posted at http://stackoverflow.com/questions/38568690/how-to-insert-a-itextsharp-text-rectangle-rectangle-at-an-absolute-position),

iTextSharp.text.Rectangle rectangle = new Rectangle(10, 10, 150, 15, 0);  
   // (lower-left-x, lower-left-y, upper-right-x (llx + width), upper-right-y (lly + height), rotation angle 
rectangle.BorderColor = BaseColor.WHITE;
rectangle.BackgroundColor = BaseColor.LIGHT_GRAY;
overContent.Rectangle(rectangle);
PdfAnnotation annotation = PdfAnnotation.CreateLink(
   stamper.Writer, rectangle, PdfAnnotation.HIGHLIGHT_INVERT,
   new PdfAction("http://itextpdf.com/") );            
stamper.AddAnnotation(annotation, 1);



我可以在生成的PDF中创建超链接。但是,超链接矩形无论我如何更改Rectangle参数中的x& y值(int x,int y,int width,int height),它总是位于生成的PDF的左下角。注释对象没有设置方法它的绝对位置。如果您有使用iTextSharp的经验,尤其是在PDF中创建超链接的知识,您能分享您的知识吗?谢谢。

// ********

这是我的问题的更新

我尝试了另一段代码下面:


I can create a hyperlink in the generated PDF. However, the Hyperlink rectangle is ALWAYS at the bottom-left of the generated PDF no matter how I change the x & y values in the Rectangle arguments (int x, int y, int width, int height). The annotation object does not have a method for setting its absolute position. If you have the experience on using iTextSharp, and particularly have the knowledge on the creation of hyperlink in the PDF, could you share your knowledge? Thanks.
// ********
This is the update of my Question
I tried another piece of code as below:

using (System.IO.FileStream fs = new FileStream(Server.MapPath("pdf") + "\\" + "PDF with graphics and images.pdf", FileMode.Create)) {
   Document document = new Document(PageSize.A4, 25, 25, 30, 30);
   PdfWriter writer = PdfWriter.GetInstance(document, fs);
   Font link = FontFactory.GetFont("Arial", 12, Font.UNDERLINE, BaseColor.BLACK);  
   iTextSharp.text.Anchor anchor = new Anchor("www.mikesdotnetting.com", link);
   anchor.Reference = "http://www.mikesdotnetting.com";
   document.Add(anchor);



此超链接也已添加,但其位置位于页面的左上角。 iTextSharp.text.Anchor让bot具有setAbsolutePosition方法。有没有办法将锚设置在所需的位置?谢谢。



我尝试了什么:



如何插入在绝对位置的iTextSharp.text.Rectangle矩形?


This hyperlink is also added but its position is on the top-left of the page. The iTextSharp.text.Anchor does bot have the setAbsolutePosition method. Is there a way to set the anchor at a desired position? Thanks.

What I have tried:

How to insert a iTextSharp.text.Rectangle rectangle at an absolute position?

推荐答案

我没有注释经验 - 但我经常需要在页面上放置一些绝对的东西而且我使用的是'假'表。如果你可以将你的注释添加到'单元',我认为你可以,试试这个



I dont have experience with annotations - but often I need to position something absolutely on a page and I use a 'fake' table. If you can add your annotation to a 'cell', and I think you can, try this

PdfContentByte cb = writer.DirectContent;
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 400f;
table.AddCell(//Annotation Details Here);
table.WriteSelectedRows(0, -1, 200, 50, cb);





您可以将表格边框设置为无论你想要什么,我都让它们看不见




好​​吧,这是我流程的基础: -





You can set the table borders to whatever you wish, I make them invisible


Ok, this is 'the base' of my process :-

PdfContentByte cb;

// Create PDF Reader For Input PDF
PdfReader reader = new PdfReader(//Source PDF File Name);

// Create Output PDF 
using (System.IO.FileStream fs = new System.IO.FileStream(//Target PDF Output File Name, System.IO.FileMode.Create))
{
    // Create PDF Stamper
    PdfStamper pdfStamper = new (PdfStamper, fs);

    // Get The Content Bytes For Page 1 
    cb = pdfStamper.GetOverContent(1);

    // Not Sure If this is needed 
    cb.BeginText();

    // Create a table and set a width

    PdfPTable table = new PdfPTable(1);
    table.TotalWidth = 400f;
    
    // Option 1 or Option 2 Here - I usually use 'builder' procedures for Tables/Paragraphs/Cells

    // Write the table at an absolute position 
    table.WriteSelectedRows(0, -1, 200, 50, cb);

    // If We've needed to use BeginText() We need this 
    cb.EndText();

    pdfStamper.FormFlattening = true;
    // Close Stamper
    pdfStamper.Close();
}





然后是这两个选项中的任何一个







Then either of these two options


// Option 1 - Using Paragraph + Chunk Allows For Alignment 

// Create Chunk with anchor
var webAddress = new Chunk("CodeProject");
// Set The anchor
webAddress.SetAnchor("http://www.codeproject.com");
// Crate a paragraph to hold the chunk
var para = new Paragraph(webAddress);
// Add some alignment to the paragraph
para.Alignment = Element.ALIGN_CENTER;
// Create a cell
PdfPCell anchorCell = new PdfPCell();
// Add the paragraph to the cell
anchorCell.AddElement(para);
// Can set padding on cell :-)
anchorCell.Padding = 30f;
// Set the cell border off 
anchorCell.Border = Rectangle.NO_BORDER;
// Add the cell to the table
table.AddCell(anchorCell);
//



< br $> b $ b或





or

// Option 2 - Use Chunk, less formatting control 

// Create Chunk with anchor
var webAddress = new Chunk("CodeProject");
// Set The anchor
webAddress.SetAnchor("http://www.codeproject.com");
// Create a cell
PdfPCell anchorCell = new PdfPCell();
// Add the webAddress (chunk) to the cell
anchorCell.AddElement(webAddress);
// Set the cell border off 
anchorCell.Border = Rectangle.NO_BORDER;
// Add the cell to the table
table.AddCell(anchorCell);
//





你需要设置



//来源PDF文件名

//目标PDF输出文件名



到PDF文件的值(我用它作为'底层')和PDF文件出来



btw - 这是从手写笔记输入的,我在我的Mac上,暂时无法进入我的开发机器,所以可能需要在这里和那里进行一些编辑



你可以在这里复制选项1或2(或者制作一个静态程序并传入cb / ContentBytes





You'll need to set

//Source PDF File Name
//Target PDF Output File Name

To values for a PDF file in (I use this as an 'underlay') and a PDF file out

btw - this is typed up from handwritten notes, Im on my mac and cant get to my dev machine at the moment, so it may need a bit of editing here and there

You can copy Option 1 or 2 in here (or make a static procedure and pass in cb / ContentBytes

Quote:

//选项1或选项2这里 - 我通常使用表格/段落/单元格的'构建器'程序

// Option 1 or Option 2 Here - I usually use 'builder' procedures for Tables/Paragraphs/Cells





..正如它所说,我通常有一组'建造者',允许我组装字体,块中的段落,单元格中的表格等等





完成工作示例(从头开始创建PDF)





.. as it says, I usually have a set of 'builders' that allow me to assembly fonts, paragraphs from chunks, tables from cells etc


Complete working example (Create PDF From scratch)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace CPPDF001
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseFont bfTimesRoman = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

            Font fTimesRomanItalic10 = new Font(bfTimesRoman, 10, Font.ITALIC, BaseColor.BLACK);

            String testPDFName = "CPPFF001.pdf";
            if (File.Exists(testPDFName))
            {
                File.Delete(testPDFName);
            }

            using (FileStream fs = new FileStream("CPPFF001.pdf", FileMode.Create))
            {
                Document doc = new Document(PageSize.A4, 25,25,30,30);
                PdfWriter writer = PdfWriter.GetInstance(doc, fs);

                doc.Open();
                PdfContentByte cb = writer.DirectContent;

                cb.BeginText();

                writeText(cb, "Garth Was Here !!!", 30, 718, bfTimesRoman, 14);

                // Note the implications of this wrt chunks in Try 1 and Try 2
                cb.SetFontAndSize(bfTimesRoman, 10);

                PdfPTable table = new PdfPTable(1);
                table.TotalWidth = 400f;

                // Try 1 : This works - NB Will Have a Rectangle Around it
                // Note that because we're using a chunk, its font/size is
                // dependand upon the statement :-
                //
                // cb.SetFontAndSize(bfTimesRoman, 10);
                //
                
                var chunk = new Chunk("CodeProject");
                chunk.SetAnchor("http://www.codeproject.com");
                chunk.SetUnderline(0.5f, -1.5f);

                PdfPCell cell = new PdfPCell();
                cell.AddElement(chunk);
                table.AddCell(cell);
                table.WriteSelectedRows(0, -1, 30, 646, cb);
                // Try 1 End


                // Try 2 : This also works - NB Will not have a Border/Rectangle Around it
                // Note that because we're using a chunk, its font/size is
                // dependand upon the statement :-
                //
                // cb.SetFontAndSize(bfTimesRoman, 10);
                //

                PdfPTable table1 = new PdfPTable(1);
                table1.TotalWidth = 100f;

                PdfPCell cell1 = new PdfPCell();
                cell1.AddElement(chunk);
                cell1.Border = Rectangle.NO_BORDER;

                table1.AddCell(cell1);
                table1.WriteSelectedRows(0, -1, 30, 574, cb);
                // Try 2 End

                // Try 3 : This also works 
                //   NB Will not have a Border/Rectangle Around it
                //      Will Be In Italic, No Underline

                PdfPTable table2 = new PdfPTable(1);
                table2.TotalWidth = 100f;

                PdfPCell cell2 = new PdfPCell();

                // Note the chunk formatting here :-)
                var chunk1 = new Chunk("CodeProject", fTimesRomanItalic10);
                chunk1.SetAnchor("http://www.codeproject.com");

                //var paragraph = new Paragraph(chunk1); 
                cell2.AddElement(chunk1);
                cell2.Border = Rectangle.NO_BORDER;

                table2.AddCell(cell2);
                table2.WriteSelectedRows(0, -1, 30, 502, cb);
                // Try 3 End

                cb.EndText();
                doc.Close();

            } // using

        } // Main

        static void writeText(PdfContentByte cb, string text, int x, int y, BaseFont font, int size)
        {
            cb.SetFontAndSize(font, size);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
        }

        // Obviously you'd re-factor Try1-3 Into Code that looked like
        /*
           static Chunk CreateChunk(string text,
                                    string link,
                                    Font font,
                                    int fontSize)
           {
               // Create and return Chunk
           }

           static PDFPCell CreateCell(Chunk chunk,
                                    bool borderOrNot)
           {
               // Create and return Cell, using chunk
           }

           static Table CreateTable(PDFPcell cell,
                                    int rectangleSize)
           {
               // Create and return Table
           }

           static void AddAnnotation(PdfContentByte cb,
                                     string text,
                                     string link, 
                                     Font font,
                                     int fontSize,
                                     int positionX,
                                     int positionY,
                                     bool borderOrNot,
                                     int rectangleSize)
           {
                // Build Chunk using text, link, font, fontSize
                // Build Cell, Add Chunk To Cell And Turn Border Off if borderOrNot == true
                // Build Table, set width to rectangleSize
                // Write Table to cb, positionX, positionY
          
           }
        */

        }
    }
}





完整的工作示例(注释现有PDF)





Complete working example (annotating existing PDF)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace CPPDF001
{
    class Program
    {
        static void Main(string[] args)
        {
            BaseFont bfTimesRoman = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

            Font fTimesRomanItalic10 = new Font(bfTimesRoman, 10, Font.ITALIC, BaseColor.BLACK);

            //
            // ** Part 1 - Create a PDF to Stamp/Annotate **
            //

            String testPDFName = "CPPDF001.pdf";
            if (File.Exists(testPDFName))
            {
                File.Delete(testPDFName);
            }

            // Create a simple PDF to use for Underlay
            using (FileStream fs = new FileStream(testPDFName, FileMode.Create))
            {
                Document doc = new Document(PageSize.A4, 25,25,30,30);
                PdfWriter writer = PdfWriter.GetInstance(doc, fs);

                doc.Open();
                PdfContentByte cb = writer.DirectContent;

                // Note the implications of this wrt chunks in Try 1 and Try 2
                cb.SetFontAndSize(bfTimesRoman, 10);

                cb.BeginText();

                writeText(cb, "CodeProject Is Neat !!!", 30, 718, bfTimesRoman, 14);

                cb.EndText();
                doc.Close();

            } // using - PDF Creation


            //
            // ** Part 2 - Use the PDF From Part 1 and Annotate it with a Hyperlink using PDFStamp process **
            //

            String testPDFNameStamped = "CPPDF001-Stamped.pdf";
            if (File.Exists(testPDFNameStamped))
            {
                File.Delete(testPDFNameStamped);
            }

            PdfReader reader = new PdfReader(testPDFName);

            using (System.IO.FileStream fs = new System.IO.FileStream(testPDFNameStamped, System.IO.FileMode.Create))
            {
                PdfStamper pdfStamper = new PdfStamper(reader, fs);

                // reader.NumberOfPages are indexed from 1 not 0
                // depending on how your PDF has been constructed you might need to use .GetUnderContent()
                PdfContentByte cb = pdfStamper.GetOverContent(1);

                cb.BeginText();

                PdfPTable table1 = new PdfPTable(1);
                table1.TotalWidth = 100f;

                PdfPCell cell1 = new PdfPCell();

                // Note the chunk formatting here :-)
                var chunk1 = new Chunk("CodeProject", fTimesRomanItalic10);
                chunk1.SetAnchor("http://www.codeproject.com");

               
                cell1.AddElement(chunk1);
                //cell1.Border = Rectangle.NO_BORDER;

                table1.AddCell(cell1);
                table1.WriteSelectedRows(0, -1, 30, 646, cb);

                cb.EndText();

                pdfStamper.FormFlattening = true;
                pdfStamper.Close();

            } // using - PDF Stamp

        } // Main

        static void writeText(PdfContentByte cb, string text, int x, int y, BaseFont font, int size)
        {
            cb.SetFontAndSize(font, size);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
        }
    }
}


PdfContentByte cb = pdfwrite.DirectContent;
              var Rectangular = new Rectangle(56, 621, 540,385);
              Rectangular.BorderWidthLeft = 0.1f;
              Rectangular.BorderWidthRight = 0.1f;
              Rectangular.BorderWidthTop = 0.1f;
              Rectangular.BorderWidthBottom = 0.1f;
              cb.Rectangle(Rectangular);
              cb.Stroke();


这篇关于如何在绝对位置插入iTextsharp.text.rectangle矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆