Pergunta

I want to add the ability to generate a PDF of the content in my application (for simplicity, it will be text-only).

Is there any way to automatically work out how much content will fit in a single page, or to get any content that spills over one page to create a second (third, fourth, etc) page?

I can easily work it out for blocks of text - just split the text by a number of characters into a string array and then print each page in turn - but when the text has a lot of white space and character returns, this doesn't work.

Any advice?

Current code:

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);
    }
Foi útil?

Solução

You can download PDFsharp together with MigraDoc. MigraDoc will automatically add pages as needed, you just create a document and add your text as paragraphs.

See MigraDoc samples page:
http://pdfsharp.net/wiki/MigraDocSamples.ashx

Outras dicas

MigraDoc is the recommended way.

If you want to stick to PDFsharp, you can use the XTextFormatter class (source included with PDFsharp) to create a new class that also supports page breaks (e.g. by returning the count of chars that fit on the current page and have the calling code create a new page and call the formatter again with the remaining text).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top