草庐IT

ios - 在 Objective C 中将包含 UILabel、UIImageView 和 UITableView 的 UIView 保存为 PDF

coder 2024-01-23 原文

我的 iOS 应用程序将选定的联系人详细信息保存为 PDF 并将其显示在 WebView 中。
我的 View 显示选定的联系人图像(在 UIImage 中)、姓名(在 UILabel 中)和其他详细信息,如电话号码(在 UITableView 中) ).
现在,我需要将此 View 保存为 PDF 并在另一个 View 中查看它。
我现在使用的方法 createPDFfromUIView 将我的 View 保存为 PDF。

但我无法在我的 PDF 中看到整个表格 View 。
我需要滚动才能看到整个表格 View 。

我该如何解决这个问题?

-(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();

    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
    [aView.layer renderInContext:UIGraphicsGetCurrentContext()];

    // remove PDF rendering context
    UIGraphicsEndPDFContext();

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

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

    // instructs the mutable data object to write its context to a file on disk
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

最佳答案

成功了!

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename

{ CGRect priorBounds = self.contactDetails.bounds; CGSize fittedSize = [self.contactDetails sizeThatFits:CGSizeMake(priorBounds.size.width, self.contactDetails.contentSize.height)]; self.contactDetails.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height);

CGRect pdfPageBounds = CGRectMake(0, 30, 312, 800); // Change this as your need
NSMutableData *pdfData = [[NSMutableData alloc] init]; // Creates a mutable data object for updating with binary data, like a byte array

CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [UIColor redColor].CGColor);
CGContextFillRect(UIGraphicsGetCurrentContext(), _detailView.bounds);

UIGraphicsBeginPDFContextToData(pdfData, _detailView.bounds, nil);
{

    int page = 1;
    for (CGFloat pageOriginY = 0; pageOriginY < fittedSize.height; pageOriginY += pdfPageBounds.size.height)
    {

        if(page == 1)
        {
            UIGraphicsBeginPDFPageWithInfo(_detailView.bounds, nil);

            CGContextSaveGState(UIGraphicsGetCurrentContext());
            {


                [_contactImage.image drawInRect:CGRectMake( 200, 10, _contactImage.bounds.size.width, _contactImage.bounds.size.height)];
                NSDictionary *attributes = @{
                                             NSFontAttributeName   : [UIFont fontWithName:@"Arial" size:20],
                                             NSStrokeWidthAttributeName    : @(0),
                                             NSStrokeColorAttributeName    : [UIColor blackColor]
                                             };
                [_contactName.text drawAtPoint:CGPointMake(30 , 50) withAttributes:attributes];


                CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, 130);
                [self.contactDetails.layer renderInContext:UIGraphicsGetCurrentContext()];


            } CGContextRestoreGState(UIGraphicsGetCurrentContext());

        }
        else
        {
            UIGraphicsBeginPDFPageWithInfo(_detailView.bounds, nil);
            CGContextSaveGState(UIGraphicsGetCurrentContext());
            {
                CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, -pageOriginY);
                [self.contactDetails.layer renderInContext:UIGraphicsGetCurrentContext()];

            } CGContextRestoreGState(UIGraphicsGetCurrentContext());
        }
        page++;
    }

} UIGraphicsEndPDFContext();

self.contactDetails.bounds = priorBounds; // Reset the tableView


// Use the pdfData to
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString* filePathPDF = [documentsPath stringByAppendingPathComponent:@"myPdf.pdf"]; //Add the file name
BOOL written = [pdfData writeToFile:filePathPDF atomically:YES];

关于ios - 在 Objective C 中将包含 UILabel、UIImageView 和 UITableView 的 UIView 保存为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894881/

有关ios - 在 Objective C 中将包含 UILabel、UIImageView 和 UITableView 的 UIView 保存为 PDF的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  3. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  4. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  7. ruby-on-rails - Prawn PDF : I need to generate nested tables - 2

    我需要一个表,其中行实际上是2行表,一个嵌套表是..我怎样才能在Prawn中做到这一点?也许我需要延期..但哪一个? 最佳答案 现在支持子表:Prawn::Document.generate("subtable.pdf")do|pdf|subtable=pdf.make_table([["sub"],["table"]])pdf.table([[subtable,"original"]])end 关于ruby-on-rails-PrawnPDF:Ineedtogeneratenested

  8. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  9. ruby - 在 Ruby 中将整数格式化为固定长度的字符串 - 2

    有没有一种简单的方法可以将给定的整数格式化为具有固定长度和前导零的字符串?#convertnumberstostringsoffixedlength3[1,12,123,1234].map{|e|???}=>["001","012","123","234"]我找到了解决方案,但也许还有更聪明的方法。format('%03d',e)[-3..-1] 最佳答案 如何使用%1000而不是进行字符串操作来获取最后三位数字?[1,12,123,1234].map{|e|format('%03d',e%1000)}更新:根据theTinMan的

  10. ruby-on-rails - 使用包含多个关联和单独的条件 - 2

    我的Gallery模型中有以下查询:media_items.includes(:photo,:video).rank(:position_in_gallery)我的图库模型有_许多媒体项,每个都有一个照片或视频关联。到目前为止,一切正常。它返回所有media_items包括它们的photo或video关联,由media_item的position_in_gallery属性排序。但是我现在需要将此查询返回的照片限制为仅具有is_processing属性的照片,即nil。是否可以进行相同的查询,但条件是返回的照片等同于:.where(photo:'photo.is_processingIS

随机推荐