Printing Off-screen PDFViews

隐身守侯 提交于 2019-11-29 11:35:08
alex-i

Had the exact same problem. The PDFView needs to be added to a NSWindow in order for printWithInfo:autoRotate: to work (atleast in my case), otherwise the printing controls go blank or won't work.

Here's the complete code:

    PDFView *vDoc = [[PDFView alloc] init];
    [vDoc setDocument:pdfDoc];
    [vDoc setAutoScales: YES];
    [vDoc setDisplaysPageBreaks: NO];
    NSWindow *wnd = [[NSWindow alloc] init];
    [wnd setContentSize:vDoc.frame.size];
    [wnd setContentView:vDoc];
    [vDoc printWithInfo:printInfo autoRotate:YES];
    [wnd release];
    [vDoc release];

PDFView is a subclass of NSView. The designated initializer for NSView is -initWithFrame: ... if you don't use -initWithFrame: strange things can happen. Since PDFView has no other designated initializers, -initWithFrame: is it. I'm guessing that's at least part of your problem.

Another part may be memory related. Are you using garbage collection or not? If you are, you're not keeping a reference to your PDFView anywhere, so may be getting deallocated. If you aren't using garbage collection, you're leaking your PDFView (also because you keep no reference to it, so you can release it when you're done). Same with your myView NSView instance ... you're leaking it if you're not using GC.

Building on alex-i's excellent answer, I added the following lines so the print dialog showed up in a user-friendly location:

NSRect windowRect = self.window.frame;
NSPoint printTopLeftPoint = NSMakePoint(CGRectGetMidX(windowRect), CGRectGetMaxY(windowRect));
[wnd setFrameTopLeftPoint:printTopLeftPoint];

My self.window is for my current window controller, not the temporary window.

I like alex-i's answer because it does not use private APIs. But in my case, I already have a window (and I suppose in most cases you would!), so I figured I would use that window instead of creating one. Here is what I ended up doing, using swift:

func print(_ pdfDocument: PDFDocument, using window: NSWindow) {

    // create a hidden pdf view with the document
    let pdfView = PDFView()
    pdfView.document = pdfDocument
    pdfView.autoScales = true
    pdfView.displaysPageBreaks = false
    pdfView.frame = NSMakeRect(0.0, 0.0, 50.0, 50.0)
    pdfView.isHidden = true

    // add the view to the window and print
    window.contentView.addSubview(pdfView)
    pdfView.print(nil)
    pdfView.removeFromSuperview()

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!