如何以编程方式为mac App设置打印选项的页面布局

时间:2011-05-03 12:33:14

标签: cocoa macos printing

我需要使用我的mac应用程序打印视图的内容。我得到了打印选项的标准面板。但是在预览我的页面设置时却不合适。

我正在使用以下代码对打印按钮执行操作

- (void)print:(id)sender {


        [[NSPrintOperation printOperationWithView:staticText] runOperation];
        float horizontalMargin, verticalMargin;

        NSSize bounds = [printInfo imageablePageBounds].size;
        NSSize size = [printInfo paperSize];

        horizontalMargin = 0;
        verticalMargin = 0;
        [self setPrintInfo:[NSPrintInfo sharedPrintInfo]];

        [printInfo setLeftMargin:horizontalMargin];
        [printInfo setRightMargin:horizontalMargin];
        [printInfo setTopMargin:verticalMargin];
        [printInfo setBottomMargin:verticalMargin];


    }

have a look at the image attached

3 个答案:

答案 0 :(得分:9)

经过大量的研究,我得到了一切正常。我正在使用下面的代码&想分享可能会对将来有所帮助

    [self setPrintInfo:[NSPrintInfo sharedPrintInfo]];
    [printInfo setVerticalPagination:NSAutoPagination];
    float horizontalMargin, verticalMargin;

    horizontalMargin = 0;
    verticalMargin = -100;

    [printInfo setLeftMargin:horizontalMargin];
    [printInfo setRightMargin:horizontalMargin];
    [printInfo setHorizontallyCentered:YES];
    [printInfo setTopMargin:-600];

    [printInfo setBottomMargin:verticalMargin];
    [[NSPrintOperation printOperationWithView:sampleText] runOperation];

答案 1 :(得分:3)

我自己遇到了这个问题。

我的解决方案是在Swift中执行此操作:

let printInfo = NSPrintInfo.sharedPrintInfo()
let printOperation = NSPrintOperation(view: webView.mainFrame.frameView.documentView, printInfo: printInfo)
printOperation.printInfo.orientation = NSPaperOrientation(rawValue: 1)! // switch to landscape
printOperation.printInfo.leftMargin = 10
printOperation.printInfo.rightMargin = 10
printOperation.printInfo.topMargin = 10
printOperation.printInfo.bottomMargin = 10
printOperation.runOperation()

NSPaperOrientation采用整数值(0 =纵向,1 =横向)

虽然可以稍微整理一下。

答案 2 :(得分:0)

C#版本的John Griffiths答案以防万一有人在Xamarin.Mac

  var printInfo = NSPrintInfo.SharedPrintInfo;
  var printOperation = NSPrintOperation.FromView(webContainer.MainFrame.FrameView.DocumentView, printInfo);

  printOperation.PrintInfo.Orientation = NSPrintingOrientation.Portrait;
  printOperation.PrintInfo.LeftMargin = 20;
  printOperation.PrintInfo.RightMargin = 20;
  printOperation.PrintInfo.TopMargin = 50;
                printOperation.PrintInfo.BottomMargin = 50;
                printOperation.RunOperation();