You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NSPrintPanel默认打印预览多页面不同方向显示异常问题

解决Cocoa打印预览中多页不同方向显示异常的问题

问题根源

  • 仅在rectForPage:中调整页面方向无法生效,因为NSPrintInfo的orientation属性默认全局生效,打印预览会沿用最后一次设置的全局方向,而PDF导出是逐页独立处理,因此出现结果不一致的情况。
  • 页面空白是因为PrintView未实现drawRect:方法绘制内容。

解决方案

要让预览正确识别每一页的方向,需为每一页单独配置NSPrintInfo,并通过NSPrintOperation的setPrintInfo:forPage:方法绑定到对应页面,同时补充绘制逻辑解决页面空白问题。

修正后的完整代码

1. 调整PrintView类,添加绘制逻辑

#import <Cocoa/Cocoa.h>

@interface PrintView : NSView
@property (nonatomic, assign) NSInteger totalPages;
@end

@implementation PrintView

- (NSRect)rectForPage:(NSInteger)page {
    NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
    NSRect pageRect = printInfo.paperRect;
    
    // 根据页码调整页面区域尺寸(匹配方向)
    if (page % 2 == 0) { // 偶数页横向,交换宽高
        pageRect = NSRectMake(pageRect.origin.x, pageRect.origin.y, pageRect.size.height, pageRect.size.width);
    }
    return pageRect;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    
    // 获取当前页码并绘制,解决页面空白
    NSInteger currentPage = [[NSPrintOperation currentOperation] currentPage];
    NSString *pageText = [NSString stringWithFormat:@"Page %ld", (long)currentPage];
    
    NSRect textRect = self.bounds;
    NSDictionary *attributes = @{NSFontAttributeName: [NSFont systemFontOfSize:24]};
    [pageText drawInRect:textRect withAttributes:attributes];
}

@end

2. 发起打印的代码(示例在ViewController中)

#import "ViewController.h"
#import "PrintView.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)startPrint:(id)sender {
    PrintView *printView = [[PrintView alloc] initWithFrame:NSZeroRect];
    printView.totalPages = 3; // 设置总页数
    
    NSPrintInfo *basePrintInfo = [NSPrintInfo sharedPrintInfo];
    NSPrintOperation *printOp = [NSPrintOperation printOperationWithView:printView printInfo:basePrintInfo];
    printOp.showsPrintPanel = YES;
    printOp.showsProgressPanel = YES;
    
    // 为每一页绑定独立的打印配置
    for (NSInteger page = 1; page <= printView.totalPages; page++) {
        NSPrintInfo *pagePrintInfo = [basePrintInfo copy];
        pagePrintInfo.orientation = (page % 2 == 0) ? NSPrintInfoOrientationLandscape : NSPrintInfoOrientationPortrait;
        [printOp setPrintInfo:pagePrintInfo forPage:page];
    }
    
    [printOp runOperation];
}

@end

关键说明

  • setPrintInfo:forPage:方法可以为指定页码绑定独立的打印配置,包括页面方向,确保打印预览和实际打印都能正确识别每一页的方向。
  • 补充的drawRect:方法绘制了页码,既解决了页面空白问题,也方便验证不同页面的方向效果。
  • 测试时,打印预览会显示第1页纵向、第2页横向、第3页纵向,导出PDF的结果也会保持一致。

内容的提问来源于stack exchange,提问作者asethone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 01:43:28