【发布时间】:2011-08-14 17:43:28
【问题描述】:
我正在尝试使用直接 HTML 打印文件,但是在将图像添加到打印文件时遇到了困难。
如何在我要打印的 HTML 中引用我的项目中的图像? UIMarkupTextPrintFormatter 是否支持标签?
【问题讨论】:
标签: objective-c ios cocoa-touch airprint
我正在尝试使用直接 HTML 打印文件,但是在将图像添加到打印文件时遇到了困难。
如何在我要打印的 HTML 中引用我的项目中的图像? UIMarkupTextPrintFormatter 是否支持标签?
【问题讨论】:
标签: objective-c ios cocoa-touch airprint
实际上比我想象的要简单得多:
NSString *yourImagePath = [[[NSBundle mainBundle] URLForResource:@"resource" withExtension:@"extension"] absoluteString];
然后您可以将图像路径放在<img> 中,它会渲染图像!瞧!
【讨论】:
UIPrintInteractionController 时它对我有用,但当我尝试使用 UIGraphicsBeginPDFContextToData 创建 PDF 文件时它不起作用
我整天都在做这个,无论我如何将图像合并到我的打印作业中,它似乎总是无法渲染它们。我尝试了多种方法。 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
在开发计算机上的 safari 中呈现相同的 html
【讨论】:
本地图片应该首先放在一个imageView中,然后转换为base64值并在html中的image标签中使用它。
let imageData:NSData = UIImagePNGRepresentation(imageView.image!)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
var imageTag = String(format: "<img src=\"data:image/png;base64,%@\"", strBase64)
【讨论】: