繁体   English   中英

在iOS 11上使用自定义字体从HTML生成PDF

[英]Using custom font to generate PDF from HTML on iOS 11

我正在尝试从HTML模板生成PDF文件。 通常,除了一件事之外,这种方法还可以。 当我尝试使用捆绑包中包含的自定义字体AvenirLTStd-Black时,我得到了PDF中的空文本,但在webView中看起来不错。 我也看不到捆绑包中的图像。 因此,我可以假定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。 这是我的解决方案:

  1. 将带有基本url(可以找到您的字体文件)的HTML字符串加载到UIWebView中。
  2. 加载Web视图后,通过UIWebView的viewPrintFormatter方法获取UIViewPrintFormatter。
  3. 使用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];
}

暂无
暂无

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

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