2014-01-20 21 views
1

我想添加在我的应用程序中生成内容PDF的能力(为了简单起见,它将仅为纯文本)。PDFsharp可以自动将字符串分割成多个页面吗?

有没有什么办法可以自动计算出多少内容适合单个页面,或者获取任何溢出一页的内容来创建第二个(第三,第四等)页面?

我可以很容易地解决它的文本块 - 只是将文本分割成字符串数组,然后依次打印每个页面 - 但是当文本有很多空白和字符返回时,这不起作用。

有什么建议吗?

当前代码:

public void Generate(string title, string content, string filename) 
    { 
     PdfDocument document = new PdfDocument(); 
     PdfPage page; 
     document.Info.Title = title; 

     XFont font = new XFont("Verdana", 10, XFontStyle.Regular); 

     List<String> splitText = new List<string>(); 
     string textCopy = content; 
     int ptr = 0; 
     int maxCharacters = 3000; 
     while (textCopy.Length > 0) 
     { 
      //find a space in the text near the max character limit 
      int textLength = 0; 
      if (textCopy.Length > maxCharacters) 
      { 
       textLength = maxCharacters; 

       int spacePtr = textCopy.IndexOf(' ', textLength); 
       string startString = textCopy.Substring(ptr, spacePtr); 
       splitText.Add(startString); 

       int length = textCopy.Length - startString.Length; 
       textCopy = textCopy.Substring(spacePtr, length); 
      } 
      else 
      { 
       splitText.Add(textCopy); 
       textCopy = String.Empty; 
      } 
     } 

     foreach (string str in splitText) 
     { 
      page = document.AddPage(); 

      // Get an XGraphics object for drawing 
      XGraphics gfx = XGraphics.FromPdfPage(page); 
      XTextFormatter tf = new XTextFormatter(gfx); 
      XRect rect = new XRect(40, 100, 500, 600); 
      gfx.DrawRectangle(XBrushes.Transparent, rect); 
      tf.DrawString(str, font, XBrushes.Black, rect, XStringFormats.TopLeft); 
     } 

     document.Save(filename); 
    } 

回答

1

MigraDoc是推荐的方式。

如果你想坚持使用PDFsharp,你可以使用XTextFormatter类(PDFsharp包含的源代码)来创建一个新的类,它也支持分页符(例如通过返回适合当前页面的字符数并调用代码将创建一个新页面并使用剩余的文本再次调用格式化程序)。