【问题标题】:Using custom font to generate PDF from HTML on iOS 11在 iOS 11 上使用自定义字体从 HTML 生成 PDF
【发布时间】:2019-04-02 14:09:56
【问题描述】:

我正在尝试从 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)
}

Link to original tutorial

【问题讨论】:

    标签: html ios css swift pdf


    【解决方案1】:

    我遇到了类似的问题,我想在 iOS 中使用自定义字体打印 HTML。这是我的解决方案:

    1. 将带有基本 url(可以找到您的字体文件)的 HTML 字符串加载到 UIWebView。
    2. 网页视图加载完成后,通过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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 2017-05-08
      • 2017-07-01
      • 2021-11-26
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多