How to Add Images in UIMarkupTextPrintFormatter?

穿精又带淫゛_ 提交于 2019-12-04 00:34:19

It's actually much simpler than I thought:

NSString *yourImagePath = [[[NSBundle mainBundle] URLForResource:@"resource" withExtension:@"extension"] absoluteString];

Then you can put the image path in an <img> and it will render the image! Voila!

I have been at this all day, and no matter how I incorporate images into my print jobs, it always seems to not render them. I have tried multiple methods. 1) Base64 embedding image data, 2) Filepath URL eg. "file:///localhost/...", 3) String based file paths "/Applications/....". I have been storing the images in my sandbox Documents directory and nothing has rendered out. Everything else in the pdf is fine. I also attempted the above and to no avail not even images from the bundle will render out. What gives? I even out put the html to a file and loaded up in safari on my computer (since testing in simulator the absolute paths are the same) and it works.

Source

+ (NSData*)renderMarkup:(NSString*)markup
{
  UIMarkupTextPrintFormatter *formatter = [[UIMarkupTextPrintFormatter alloc] initWithMarkupText:markup];

  SBAnnotationPrintPageRenderer *renderer = [[SBAnnotationPrintPageRenderer alloc] init];
  [renderer addPrintFormatter:formatter startingAtPageAtIndex:0];
  renderer.footerHeight = 10;
  renderer.headerHeight = 10;

  NSMutableData * pdfData = [NSMutableData data];
  UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);

  for (NSInteger i = 0; i < [renderer numberOfPages]; i++)
  {
    UIGraphicsBeginPDFPage();

    CGRect bounds = UIGraphicsGetPDFContextBounds();
    [renderer drawPageAtIndex:i inRect:bounds];
  }

  UIGraphicsEndPDFContext();

  return pdfData;
}

And the generated Html

<table>
    <tr>
        <td>
            <img style='background-color:blue;' src='/Users/zachthayer/Library/Application Support/iPhone Simulator/6.1/Applications/A47C1BDF-DCD1-49A5-A452-59802AEC2A94/Documents/29161AFF-BE35-4EEE-A7A1-ACF2DA9ABA71.png'/>
        </td>
        <td>
            <h2>Superadmin</h2>
            <i>00:00:00:00</i>
            <p>Test note</p>
        </td>
    </tr>
</table>

And the Rendered PDF

Same html rendered in safari on the development computer

Locally Images should be first placed inside a imageView and then converted to base64 value and use it inside the image tag in html.

let imageData:NSData = UIImagePNGRepresentation(imageView.image!)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
var imageTag = String(format: "<img src=\"data:image/png;base64,%@\"", strBase64)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!