【发布时间】:2011-05-06 13:11:23
【问题描述】:
我可以用 SharpPDF 添加段落,而不必指定确切的坐标吗?我不能把段落放在另一个之下吗?
请告诉我您是否使用过该库。
【问题讨论】:
-
我很乐意,如果它只是解释换行符。 @Ryan 有什么好运气吗?
标签: c# pdf-generation
我可以用 SharpPDF 添加段落,而不必指定确切的坐标吗?我不能把段落放在另一个之下吗?
请告诉我您是否使用过该库。
【问题讨论】:
标签: c# pdf-generation
不可能在不指定坐标的情况下一个接一个地添加段落,但是我确实编写了这个示例,它将在页面中向下移动段落并在必要时创建一个新页面。在这个愿望中,您可以写出文本、段落、绘图,并且始终知道“光标”的位置。
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 位置。
【讨论】: