【发布时间】:2016-05-29 04:32:48
【问题描述】:
我正在尝试在现有 PDF(显示在屏幕上)上绘制图像。最终目标是在任何地方签署 pdf。
My sample code is here on Github
代码(基本)是这样工作的:
- 用户点击他想要绘制图像的位置
- 进行 PDF 编辑,最终的 PDF 出现在屏幕上
但问题是我的图像看起来是颠倒的。在使用 PDF 时,我了解到您必须翻转上下文才能呈现,这可能是相关的。
- (void)editPDFWithName:(NSString*)pdfName
{
// grab reference to bundled PDF
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[[NSBundle mainBundle] URLForResource:pdfName withExtension:@"pdf"]);
const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);
// Begin PDF context
NSMutableData* data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);
// loop over PDF pages to render it
for(size_t page = 1; page <= numberOfPages; page++)
{
// Get the current page and page frame
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
// Draw the page (flipped)
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
// Y axis is negative in order to render PDF (mandatory)
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
CGContextDrawPDFPage(ctx, pdfPage);
CGContextRestoreGState(ctx);
if(page == [self getCurrentPage])
{
// 0.75f factor to convert pixel/points
CGContextDrawImage(ctx, CGRectMake(self.xTouchCoord*0.75f, self.yTouchCoord*0.75f, self.logo.size.width, self.logo.size.height), self.logo.CGImage);
}
}
UIGraphicsEndPDFContext();
CGPDFDocumentRelease(pdf);
pdf = nil;
// Save PDF
[self savePDF:data];
}
I tried multiple ways to flip image as suggested on this post
但图像仍然翻转。
我注意到的一件事是如果我在图像上使用drawAtPoint方法,它看起来没有翻转但没有出现在指定位置,就像有一个偏移量(see other post here)
有人可以提出任何想法吗?我赌的是保存和恢复上下文方法,但不能让它工作。
【问题讨论】: