如何创建段落而不指定每个在SharpPDF中的精确坐标?
答
不可能在不指定坐标的情况下一个接一个地添加段落,但是我确实写了这个示例,它会将段落向下移动到页面上,并在必要时创建一个新页面。在这个想要你可以写出文本,段落,绘图,并且总是知道“光标”的位置。
const int WIDTH = 500;
const int HEIGHT = 792;
pdfDocument myDoc;
pdfPage currentPage;
private void button1_Click(object sender, EventArgs e)
{
int height = 0;
myDoc = new pdfDocument("TUTORIAL", "ME");
currentPage = myDoc.addPage(HEIGHT, WIDTH);
string paragraph1 = "All the goats live in the land of the trees and the bushes, "
+ " when a person lives in the land of the trees and the bushes they wonder about the sanity"
+ " of it all. Whatever.";
string paragraph2 = "Redwood National and State Parks is located in northernmost coastal "
+ "California — about 325 miles north of San Francisco, Calif. Roughly 50 miles long, the parklands"
+ "stretch from near the Oregon border in the north to the Redwood Creek watershed southeast of"
+ "Orick, Calif. Five information centers are located along this north-south corrdior. Park "
+ "Headquarters is located in Crescent City, Calif. (95531) at 1111 Second Street.";
int iYpos = HEIGHT;
for (int ix = 0; ix < 10; ix++)
{
height = GetStringHeight(paragraph1, new Font("Helvetica", 12), WIDTH);
iYpos = CheckHeight(height, iYpos);
currentPage.addParagraph(paragraph1, 0, iYpos, sharpPDF.Enumerators.predefinedFont.csHelvetica, 12, WIDTH);
iYpos -= height;
height = GetStringHeight(paragraph2, new Font("Helvetica", 12), WIDTH);
iYpos = CheckHeight(height, iYpos);
currentPage.addParagraph(paragraph2, 0, iYpos, sharpPDF.Enumerators.predefinedFont.csHelvetica, 12, WIDTH);
iYpos -= height;
}
string tmp = Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".pdf";
myDoc.createPDF(tmp);
}
private int GetStringHeight(string text, Font font, int width)
{
Bitmap b = new Bitmap(WIDTH, HEIGHT);
Graphics g = Graphics.FromImage((Image)b);
SizeF size = g.MeasureString(text, font, (int)Math.Ceiling((float)width/72F * g.DpiX));
return (int)Math.Ceiling(size.Height)
}
private int CheckHeight(int height, int iYpos)
{
if (height > iYpos)
{
currentPage = myDoc.addPage(HEIGHT, WIDTH);
iYpos = HEIGHT;
}
return iYpos;
}
Y在这个API中倒退,所以792是TOP,0是BOTTOM。我使用一个Graphics对象来测量字符串的高度,因为Graphics是以像素为单位的,而Pdf是以点为单位的,我估计它们是相似的。然后我从剩余的Y值中减去高度。
在这个例子中,我不断地加入paragraph1
和paragraph2
,随着我一起更新我的Y位置。当我到达页面底部时,我创建一个新页面并重置我的Y位置。
这个项目多年来一直没有看到任何更新,但源代码是可用的,使用类似于我所做的一些事情可以使你自己的功能,允许你连续添加段落跟踪CURSOR在哪些方面认为应该继续下一步的位置。
我很喜欢,如果它只是解释换行符。还有什么好运的,@Ryan? – Jules 2011-06-24 09:32:24