2011-05-06 28 views

回答

1

不可能在不指定座標的情況下一個接一個地添加段落,但是我確實寫了這個示例,它會將段落向下移動到頁面上,並在必要時創建一個新頁面。在這個想要你可以寫出文本,段落,繪圖,並且總是知道「光標」的位置。

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在哪些方面認爲應該繼續下一步的位置。

相關問題