我正在尝试从 HTML 模板生成 PDF 文件。一般来说,除了一件事,这种方法工作正常。 当我尝试使用包含在我的包中的自定义字体 AvenirLTStd-Black 时,我在 PDF 中得到空文本,但它在 webView 中看起来很好。我也看不到我的 bundle 中的图像。所以我可以假设 UIMarkupTextPrintFormatter 看不到我的字体文件和图像。 我的假设正确吗?对此有任何解决方法吗?
这是CSS的一部分:
<style>
@font-face {
font-family: 'AvenirLTStd-Book';
src: url('ChampagneLimousinesItalic.ttf');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'AvenirLTStd-Heavy';
src: url('ChampagneLimousinesItalic.ttf');
font-weight: normal;
font-style: normal;
}
body, html{
margin: 0;
padding: 0;
font-family: 'AvenirLTStd-Book';
font-size: 15px;
}
生成代码:
func exportHTMLContentToPDF(HTMLContent: String) { 让 printPageRenderer = CustomPrintPageRenderer()
let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent)
printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)
let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer: printPageRenderer)
pdfFilename = "\(AppDelegate.getAppDelegate().getDocDir())/Invoice\(invoiceNumber!).pdf"
pdfData?.write(toFile: pdfFilename, atomically: true)
print(pdfFilename)
}
最佳答案
我遇到了类似的问题,我想在 iOS 中使用自定义字体打印 HTML。这是我的解决方案:
- 将带有基本 url(可以找到您的字体文件)的 HTML 字符串加载到 UIWebView 中。
- 在加载网页 View 后,通过 UIWebView 的 viewPrintFormatter 方法获取 UIViewPrintFormatter。
- 使用 UIViewPrintFormatter 进行打印。
由于我对swift不是很熟悉,下面是一些Objective-c示例代码:
加载 html 字符串:
UIWindow* window = [[UIApplication sharedApplication].delegate window];
UIWebView* webView = [[UIWebView alloc] initWithFrame:window.bounds];
[window addSubview:webView];
webView.delegate = self;
webView.hidden = YES;
[webView loadHTMLString:html baseURL:baseUrl];
获取 UIViewPrintFormatter 并打印:
#pragma UIWebViewDelegate
-(void)webViewDidFinishLoad:(UIWebView*)webView
{
UIPrintInfo* printInfo = [UIPrintInfo printInfo];
printInfo.jobName = @"Print Demo";
UIPrintInteractionController* printVC = [UIPrintInteractionController sharedPrintController];
printVC.printInfo = printInfo;
UIViewPrintFormatter* htmlFormatter = [webView viewPrintFormatter];
printVC.printFormatter = htmlFormatter;
[printVC presentAnimated:YES completionHandler:^(UIPrintInteractionController * _Nonnull printInteractionController, BOOL completed, NSError * _Nullable error) {
}];
webView.delegate = nil;
[webView removeFromSuperview];
}
关于html - 在 iOS 11 上使用自定义字体从 HTML 生成 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49799648/