簡體   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