我需要创建一个包含多个部分的PDF,并且在每个部分之后需要添加一行,但我不知道在哪里绘制这一行。
我需要找到确切的坐标[x,y],其中文档中的下一个元素将被写入。
答案 0 :(得分:8)
就像@Olaf说的那样,使用GetVerticalPosition
获取Y
。 X
只是文档的LeftMargin
。以下是针对iTextSharp 5.1.1.0的全功能WinForms应用程序,希望能够满足您的需求:
using System;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Test file name
string TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//Standard iTextSharp setup
using (FileStream fs = new FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (Document doc = new Document(PageSize.LETTER))
{
using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
{
//Open the document for writing
doc.Open();
//Will hold our current x,y coordinates;
float curY;
float curX;
//Add a paragraph
doc.Add(new Paragraph("It was the best of times"));
//Get the current Y value
curY = w.GetVerticalPosition(true);
//The current X is just the left margin
curX = doc.LeftMargin;
//Set a color fill
w.DirectContent.SetRGBColorStroke(0, 0, 0);
//Set the x,y of where to start drawing
w.DirectContent.MoveTo(curX, curY);
//Draw a line
w.DirectContent.LineTo(doc.PageSize.Width - doc.RightMargin, curY);
//Fill the line in
w.DirectContent.Stroke();
//Add another paragraph
doc.Add(new Paragraph("It was the word of times"));
//Repeat the above. curX never really changes unless you modify the document's margins
curY = w.GetVerticalPosition(true);
w.DirectContent.SetRGBColorStroke(0, 0, 0);
w.DirectContent.MoveTo(curX, curY);
w.DirectContent.LineTo(doc.PageSize.Width - doc.RightMargin, curY);
w.DirectContent.Stroke();
//Close the document
doc.Close();
}
}
}
this.Close();
}
}
}
答案 1 :(得分:7)
我相信只有y位置可用:尝试
PdfWriter.getVerticalPosition()
答案 2 :(得分:2)
确实只有y位置。
但是如果需要渲染一些简单的文本,然后放一张图片或画一条线,他总是可以计算渲染文本的大小:
var chunk = new Chunk(String.Format("Sample text {0}", ));
document.Add(new Paragraph(t));
float curY = writer.GetVerticalPosition(false);
float x = document.Left + chunk.GetWidthPoint();
答案 3 :(得分:1)
如果你只需要在当前部分之后画一条线,也许你不需要知道当前的x和y。 试试这个:
iTextSharp.text.pdf.draw.DottedLineSeparator sepLINE = new iTextSharp.text.pdf.draw.DottedLineSeparator();
sepLINE.LineWidth = 1;
sepLINE.Gap = 2;
sepLINE.Percentage = 50;
sepLINE.LineColor = new iTextSharp.text.BaseColor(System.Drawing.Color.Blue);
Chunk chnkLINE = new Chunk(sepLINE);
pdfDoc.Add(chnkLINE);