我可以在不指定确切坐标的情况下使用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值中减去高度。

在此示例中,我不断重复添加paragraph1paragraph2,并在进行时更新了我的Y位置。当我到达页面底部时,我将创建一个新页面并重置我的Y位置。

该项目已经多年未见任何更新,但是源代码可用,使用与我所做的类似的操作,您可以创建自己的函数,使您可以连续添加段落来跟踪CURSOR认为下一步应该去的位置。

关于c# - 如何在不指定SharpPDF中每个段落的确切坐标的情况下创建段落?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5911931/

10-13 06:10