13

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

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

4

3 回答 3

11

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

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

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

于 2011-08-16T13:11:35.567 回答
5

我整天都在做这个,无论我如何将图像合并到我的打印工作中,它似乎总是无法渲染它们。我尝试了多种方法。1) Base64 嵌入图像数据,2) 文件路径 URL,例如。"file:///localhost/...", 3) 基于字符串的文件路径 "/Applications/...."。我一直将图像存储在我的沙箱文档目录中,并且没有渲染任何内容。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;
}

以及生成的 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>

和渲染的 PDF

渲染的 PDF

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

Safari 渲染

于 2013-04-24T00:57:42.273 回答
1

本地图像应首先放置在 imageView 中,然后转换为 base64 值并在 html 中的图像标签内使用。

let imageData:NSData = UIImagePNGRepresentation(imageView.image!)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
var imageTag = String(format: "<img src=\"data:image/png;base64,%@\"", strBase64)
于 2016-08-13T06:09:05.220 回答