简体   繁体   English

PDFSharp-第二页为空

[英]PDFSharp - Second page is empty

For some reason, when I try to create a document with multiple pages the first page is ok but all others come out empty. 出于某种原因,当我尝试创建具有多个页面的文档时,第一页就可以了,但其他所有页面都是空白的。

public PdfDocument toPdf()
{
    // Create new PDF document
    PdfDocument document = new PdfDocument();
    XGraphics gfx;
    PdfPage page;

    foreach (var p in pages)
    {
        // Create new page
        page = document.AddPage();
        page.Width = XUnit.FromMillimeter(width);
        page.Height = XUnit.FromMillimeter(height);
        gfx = XGraphics.FromPdfPage(page, XGraphicsUnit.Millimeter);
        p.drawItems(gfx);
    }
    return document;
}

Any clues? 有什么线索吗?

AFAIK there is a problem with the XGraphics when you set a non-default unit (Millimeter in your case). AFAIK当您设置非默认单位(以毫米为单位)时, XGraphics出现问题。

Maybe the second page is not empty, but content is outside the "viewport". 也许第二页不是空的,但是内容在“视口”之外。

If my guess is correct, then first page will not be correct either. 如果我的猜测是正确的,那么首页也将是不正确的。

See this case on the PDFsharp forum: 在PDFsharp论坛上查看这种情况:
http://forum.pdfsharp.net/viewtopic.php?p=9642#p9642 http://forum.pdfsharp.net/viewtopic.php?p=9642#p9642

Try to dispose the graphics object properly, like this: 尝试正确放置图形对象,如下所示:

public PdfDocument toPdf()
{
    // Create new PDF document
    PdfDocument document = new PdfDocument();
    PdfPage page;

    foreach (var p in pages)
    {
        // Create new page
        page = document.AddPage();
        page.Width = XUnit.FromMillimeter(width);
        page.Height = XUnit.FromMillimeter(height);

        using (var gfx = XGraphics.FromPdfPage(page, XGraphicsUnit.Millimeter))
        {
            p.drawItems(gfx);
        }
    }

    return document;
}

As general rule: all objects which implements IDisposable must be disposed by calling Dispose . 作为一般规则:实现IDisposable所有对象都必须通过调用Dispose The using statement does this implicit. using语句隐式执行此操作。

Since you are returning the document, it's the caller's responsibility to dispose that one. 由于您要退回该文档,因此处置者是呼叫者的责任。

As a side note: some people will tell you Dispose will be called in the Finalizer , so you don't need to call it. 附带说明:有人会告诉您Dispose将在Finalizer调用,因此您无需调用它。 This argument is invalid because: 该参数无效,因为:

a) not everybody implements IDisposable properly, and a)并非每个人都正确实现IDisposable ,并且

b) typical objects, especially graphics objects and IO objects (eg file locks), need to be disposed before they can be re-used in such a way. b)典型对象,尤其是图形对象和IO对象(例如,文件锁)必须先进行处置,然后才能以这种方式重新使用。

If this doesn't help, please make sure you don't have empty pages :-) 如果这样做没有帮助,请确保您没有空白页:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM