如何在UIMarkupTextPrintFormatter中添加图像?

hwr*_*kns 12 cocoa-touch objective-c ios airprint

我正在尝试使用直接HTML打印文件,但是,我在将图像添加到打印文件时遇到了困难.

如何在我要打印的HTML中引用项目中的图像?UIMarkupTextPrintFormatter是否支持标记?

hwr*_*kns 11

它实际上比我想象的要简单得多:

NSString *yourImagePath = [[[NSBundle mainBundle] URLForResource:@"resource" withExtension:@"extension"] absoluteString];
Run Code Online (Sandbox Code Playgroud)

然后你可以把图像路径放在一个<img>,它将渲染图像!瞧!

  • 当它被送到`UIPrintInteractionController`时它适用于我,但当我尝试使用`UIGraphicsBeginPDFContextToData'创建PDF文件时它不适用 (3认同)

小智 5

我一整天都在做这件事,无论我如何将图像合并到我的打印作业中,它似乎总是无法渲染它们。我尝试了多种方法。1) Base64 嵌入图像数据,2) 文件路径 URL,例如。"file:///localhost/...", 3) 基于字符串的文件路径 "/Applications/...."。我一直将图像存储在我的沙箱 Documents 目录中,但没有呈现任何内容。pdf中的其他所有内容都很好。我也尝试了上述方法,但即使捆绑中的图像也无法渲染,但无济于事。是什么赋予了?我什至将 html 放到一个文件中,并在我的计算机上加载到 safari 中(因为在模拟器中测试,绝对路径是相同的)并且它可以工作。

来源

+ (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;
}
Run Code Online (Sandbox Code Playgroud)

和生成的 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>
Run Code Online (Sandbox Code Playgroud)

和渲染的 PDF

渲染的 PDF

在开发计算机上的 safari 中呈现相同的 html

Safari 渲染