【问题标题】:Create PDF from UIScrollView Objective C从 UIScrollView Objective C 创建 PDF
【发布时间】:2014-02-04 19:55:10
【问题描述】:

这个问题之前已经发布过(Creating PDF from UIScrollView in iphone app),我使用的代码来自here

这里是代码

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
    // Creates a mutable data object for updating with binary data, like a byte array
    NSMutableData *pdfData = [NSMutableData data];

    // Points the pdf converter to the mutable data object and to the UIView to be converted
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();


    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData

    [aView.layer renderInContext:pdfContext];

    // remove PDF rendering context
    UIGraphicsEndPDFContext();

    // Retrieves the document directories from the iOS device
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

    // instructs the mutable data object to write its context to a file on disk
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
}

设置:我有一个 UIScrollView,里面是一个 UIView。我想保存整个 UIView(950,500px),它位于(520,500)的空间(UIScrollView 大小)中。生成的PDF只有UIScrollView的大小(520,500)

我阅读了answer,但他显然更改了代码,但它对我不起作用。我整天都在努力解决这个问题。

我是初学者,所以请指出我应该在我的问题中添加的任何我错过的内容。谢谢。

PS - 这是一个 iPad 应用程序。

【问题讨论】:

  • createPDFfromUIView: 的第一个参数是内部的UIView 还是UIScrollView?我认为应该是UIView,如果还不是这样的话。
  • @Taum 是的,我正在使用 UIView

标签: ios objective-c uiscrollview


【解决方案1】:

上下文应该具有滚动视图内容大小的大小,而不是边界。

然后你需要临时调整scrollview的大小到它的内容大小,在PDF上下文中渲染它,然后将scrollview的大小恢复到原来的大小。

UIGraphicsBeginPDFContextToData(pdfData, (CGRect){0,0, scrollView.contentSize}, nil);

CGRect origSize = scrollView.frame;
CGRect newSize = origSize;
newSize.size = scrollView.contentSize;
[scrollView setFrame:newSize];

[scrollView.layer renderInContext:pdfContext];

[scrollView setFrame:origSize];

【讨论】:

  • 我试过了,它使 PDF 的大小正确,但拉伸了原始图片。
  • @KChockey Stretch 怎么样?您是否正确调整了滚动视图的大小?
  • 你能编辑我的代码吗?我认为是因为代码行的顺序
  • 通过拉伸,我的意思是它只占用了 UIView 的一部分(大约 600 像素 - 比 UIScrollView 大,这是一个好的开始),但是将 600px 拉伸到 950px
【解决方案2】:

查看ScrollViewToPDF 示例,您将了解您需要做什么。

它使用相同的 scrollview's layer renderInContext 但这里的 PDF 是根据您的要求创建的,例如一页 PDF 或多页 PDF

注意:它捕获了 scrollView 的所有可见和不可见部分

【讨论】:

  • @Popeye :正在改进我的回答并收到您的消息,但仍然感谢您的关注。
【解决方案3】:

如果有人想知道,我找到了解决此问题的方法。

由于我的 UIView 在 UIScrollView 中,并且我为 UIView 使用了另一个类,所以当我调用该方法并选择参数aView 时,我只输入了self

所以在我的 UIView 类中,当我想要生成 PDF 时,我输入

[self createPDFfromUIView:self saveToDocumentsWithFileName:UIViewPDF];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    相关资源
    最近更新 更多