Leveraging unique typography for creating PDF files from HTML within iOS 11

I am currently working on generating a PDF file from an HTML template. Everything seems to be going smoothly with this approach, except for one issue I've encountered. When attempting to use the custom font AvenirLTStd-Black that is included in my bundle, the text appears empty in the PDF, though it displays correctly in a webView. Additionally, images from my bundle are not appearing either. It seems like UIMarkupTextPrintFormatter is unable to recognize my font files and images. Is my assumption correct? And is there a workaround for this?

Below is a snippet of the CSS being used:

@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;
}

And here is the code snippet for the generation process:

func exportHTMLContentToPDF(HTMLContent: String) { let 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)
}

Original tutorial link here

Answer №1

I had a similar issue where I needed to print HTML with custom fonts on an iOS device. Here is how I was able to solve it:

  1. First, load the HTML string along with the base URL (where your font files are located) into a UIWebView.
  2. Once the web view has loaded, obtain a UIViewPrintFormatter using the viewPrintFormatter method.
  3. Lastly, utilize the UIViewPrintFormatter to print the content.

Since my knowledge of Swift is limited, below is a sample Objective-C code snippet:

Loading the HTML string:

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];

Obtaining the UIViewPrintFormatter and printing:

#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];
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scrolling does not function properly on Android devices when utilizing skrollr.js in conjunction with multiple div elements containing the id "skrollr-body."

Having trouble with the scroll functionality in my skrollr.js animations. Everything works fine on desktop, but when I checked the rendered HTML in the browser console, I noticed that there are two divs with the same id "skrollr-body". One is empty and the ...

Steps to retrieve the chosen value and visible text from a dropdown menu when clicking a button in Angular version 7

When the button is clicked, I want to display the selected text (green..) and value (1..) from a dropdown select. I attempted using ngmodel but was only able to capture the value, and an empty option is appearing in the select field. Below is the provide ...

Move the check mark to the middle of the screen

I am a beginner in HTML and I am trying to create a logout page that should have a design similar to this: https://i.sstatic.net/ld1R1.png I attempted to create it but I am struggling to position the icon correctly and I also want the whole content to be ...

Geonames weather API experiencing issues retrieving data

Is there anyone who can assist in identifying why the geonames API is failing to retrieve data? Although it seems simple, it's not functioning as expected. For example, here is a link to the API: Below are the HTML/AJAX/PHP codes for review. Thank ...

A guide on manipulating an input field to trigger md-datepicker upon clicking

What is the best way to convert an input text into a fire md-datepicker and achieve a similar result like this? ...

The form includes Bootstrap columns and a button, but there is noticeable wasted space within the

This is the form structure I am working with: <form method="GET" action="."> <div class="container-fluid pt-2 px-5 py-3"> <div class="row g-4"> <div class= ...

Issues with XFBML Like Buttons failing to load when generating numerous posts dynamically on a single page

On my webpage containing multiple posts, I am attempting to insert a Facebook LIKE button for each post. Utilizing XFBML code, I am trying to populate like buttons under every individual post with a unique URL, corresponding to the post URL. Here is the c ...

Preventing harmful JavaScript in Django with the help of Django-CKEditor

At the moment, I am utilizing django-ckeditor so that users can provide a rich description for their profile. However, this does expose a vulnerability to malicious individuals who may attempt XSS and other forms of code injection. I am curious about the ...

What steps should I take to eliminate the white gap between the paragraph and the footer on my webpage?

If you're new to html and css, feel free to check out the url [file:///Users/CatherineDu/百度云同步盘/practice/about.html]. I'm currently working on building a simple website and facing an issue - there are unwanted white spaces between the ...

How can I extract the document that is generated when a button is clicked using BeautifulSoup?

Trying to utilize BeautifulSoup for scraping my banking website to automatically retrieve the generated PDF from monthly purchases. Successfully logging in and reaching the page with the button, but the button does not seem to be a simple link - possibly a ...

Arranging elements on top of a fixed element using JavaScript and CSS

Currently, I am implementing Javascript code that adds a div to the body of pages. The purpose of this div is to always stay at the top of the document or window, regardless of the page's design and content. Everything was functioning correctly until ...

Steps for verifying if the Prefer Cross-Fade Transitions feature is enabled on iOS 13:

To determine if Reduce Motion is enabled, we can use the code UIAccessibility.isReduceMotionEnabled. But what about the option for Prefer Cross-Fade Transitions in iOS 13? To access this setting, go to Settings, then Accessibility, navigate to the VISION ...

Tips for eliminating vuetify component class or underline from autocomplete component?

I recently implemented the autocomplete component from vuetify in my project. Now, I'm looking to either remove the default styling of the component or get rid of the underline present on the autocomplete menu. https://i.sstatic.net/IGmr3.jpg Altern ...

Concealing excess content in a vertical container with margins

I'm currently working on setting up a grid of thumbnails for my blog posts using Bootstrap 4. The columns have a size of col-md-6. Within each column, there is an anchor with a background image and a gradient overlay that transitions from black to tr ...

Select2 input field not receiving focus when navigating by tab key

When attempting to tab through the fields, I encounter an issue where the fields do not highlight as expected. Despite trying various solutions, such as the following CSS code: .select2-selection__rendered:focus { outline: none !important; box-shadow: ...

Tips on transforming button-controlled tab pages in Bootstrap 2 to Bootstrap 3

I am currently in the process of upgrading my website from Bootstrap 2 to Bootstrap 3, and I have encountered an issue with a specific control that consists of multiple sets of tab pages controlled by toggle buttons. Here is an example of the functional c ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...

Firefox failing to display input placeholder text properly when wrapped

I've been working on making my placeholder text wrap to the next line in an input field. While I found solutions that work in Chrome, I'm struggling to get it right in Firefox. After researching on Stack Overflow, I came across this question: P ...

Using Three.js to create a distorted texture video effect

Check out the example linked here for reference: In this particular project, there are two cylinders involved - an outer cylinder with an image texture and an inner cylinder with a video texture. Once the second cylinder is created and added to the scene, ...

Retrieve specific data from the database section

To ensure only verified accounts can log in to my website, I created a category called Verification in PHPMyAdmin with values of 0 (not verified) or 1 (verified). While I have successfully set up the system to update the value when an account is verified, ...