Sweeper
Sweeper

Reputation: 271525

Can't print UIWebView with text color. Why?

I have a UIWebView. I want to print the contents of it using AirPrint. I came up with this code:

@IBAction func print(_ sender: Any) {
    let printController = UIPrintInteractionController.shared

    let printInfo = UIPrintInfo(dictionary:nil)
    printInfo.outputType = UIPrintInfoOutputType.general
    printInfo.jobName = "some name"
    printController.printInfo = printInfo

    let formatter = webView.viewPrintFormatter()

    formatter.perPageContentInsets = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)
    printController.printFormatter = formatter

    printController.present(animated: true, completionHandler: nil)
}

When I run the app, a print interaction controller and everything works.

However, I have things like these in the html because I want to emphasize some text:

<span style="color: #ff0000">some text</span>

"some text" appears red in the web view, but it is black when I look at the preview in the print interaction controller! In other words, all the colors are gone!

I tried to change the HTML to:

<span style="background: #ff0000">some text</span>

but the print preview appears the same. I was very surprised because the <hr> and <h3> tags all rendered fine in the preview.

Is there a way to print colored text?

Notes:

Upvotes: 1

Views: 392

Answers (1)

Craig Grummitt
Craig Grummitt

Reputation: 2995

Take a look at this section of your CSS:

@media print {
  *,
  *:before,
  *:after {
    background: transparent !important;
    color: #000 !important;
    box-shadow: none !important;
    text-shadow: none !important;
  }

This @media print section defines extra rules for how your content looks when it is printed. link

Within this section you have a *:after element which applies content after every element on your page. link

Within the *:after section you declare a color of black (#000), even making doubly sure of black, by declaring this color as !important - giving this declaration more weight than any declaration of color in the element itself. link

So you have several options for resolving this:

  1. Simply remove the !important tag from the color line:

    color: #000;

  2. Remove the whole color line from your CSS.

  3. Remove the *:after section from your CSS.
  4. Remove the @media print section from your CSS.

It all depends on what you were specifically after.

Upvotes: 1

Related Questions