2011-02-16 38 views
6

我有一些打印字符串的代碼,但是如果字符串是這樣說的:「Blah blah blah」...並且沒有換行符,文本佔據一行。我希望能夠對字符串進行塑造,以便將字體換成紙張的尺寸。自動Word-包裝文本到打印頁面?

private void PrintIt(){ 
    PrintDocument document = new PrintDocument(); 
    document.PrintPage += (sender, e) => Document_PrintText(e, inputString); 
    document.Print(); 
} 

static private void Document_PrintText(PrintPageEventArgs e, string inputString) { 
    e.Graphics.DrawString(inputString, new Font("Courier New", 12), Brushes.Black, 0, 0); 
} 

我想我可以想出一個字符的長度,並手動自動換行,但如果有一個內置的方式做到這一點,我寧願做。謝謝!

回答

9

是的,有DrawString有能力自動文字包裝文本。您可以使用MeasureString方法來檢查指定的字符串是否可以在頁面上完全繪製,以及需要多少空間。

還有一個TextRenderer專門爲此目的。

下面是一個例子:

  Graphics gf = e.Graphics; 
     SizeF sf = gf.MeasureString("shdadj asdhkj shad adas dash asdl asasdassa", 
         new Font(new FontFamily("Arial"), 10F), 60); 
     gf.DrawString("shdadj asdhkj shad adas dash asdl asasdassa", 
         new Font(new FontFamily("Arial"), 10F), Brushes.Black, 
         new RectangleF(new PointF(4.0F,4.0F),sf), 
         StringFormat.GenericTypographic); 

在這裏,我已指定的最大的60個像素作爲寬度然後測量串會給我將需要的繪製此字符串的大小。現在如果你已經有一個尺寸,那麼你可以與返回的尺寸進行比較,看它是否將被正確繪製或截斷。

+0

你可以鏈接和示例或參考頁面? – ja72 2011-02-16 15:17:36

0

老兄即時通訊用HTML打印,總的噩夢。我想說,在我看來,你應該嘗試使用別的東西來打印文本等傳遞參數報告服務,並彈出一個PDF,用戶可以打印。

或者您可能需要計算出字符數並明確指定換行符!

+0

有一個免費的,易於使用的軟件包,我可以融入我的印刷類PDF的支持?我在打印HTML文檔方面遇到了類似的困難。 – sooprise 2011-02-16 15:16:16

+0

使用了幾次,但通常是一些管道,在服務器上安裝蒸餾器或實際上試圖生成格式* GOOGLE *。我正在使用報告服務來設置報告,然後使用PDF導出設置從我的web應用程序調用它。該系統的用戶不知道其呼叫報告服務和它的魅力,PDF彈出和用戶打印出來! HTML從未設計過打印的目的。它在屁股疼痛甚至不提供給用戶。 – Jonathan 2011-02-16 15:25:54

10

sooprise, 你問你如何處理文本太長的一頁。我也想要這個。我不得不尋找很長一段時間,但最終我發現了這一點。

http://msdn.microsoft.com/en-us/library/cwbe712d.aspx

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) 
{ 
    int charactersOnPage = 0; 
    int linesPerPage = 0; 

    // Sets the value of charactersOnPage to the number of characters 
    // of stringToPrint that will fit within the bounds of the page. 
    e.Graphics.MeasureString(stringToPrint, this.Font, 
     e.MarginBounds.Size, StringFormat.GenericTypographic, 
     out charactersOnPage, out linesPerPage); 

    // Draws the string within the bounds of the page 
    e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black, 
     e.MarginBounds, StringFormat.GenericTypographic); 

    // Remove the portion of the string that has been printed. 
    stringToPrint = stringToPrint.Substring(charactersOnPage); 

    // Check to see if more pages are to be printed. 
    e.HasMorePages = (stringToPrint.Length > 0); 
} 

希望它可以幫助