如何将整个表格视图捕获为图像,从中创建 .pdf 并通过电子邮件发送

2024-03-19

这是我第一次尝试在 iOS 中创建 .pdf 文件。 我有一个表格视图,它生成我想要在 .pdf 文件中呈现的所有数据。

这是我的代码,用于将整个表格捕获为图像,从图像生成 pdf 并通过电子邮件发送:

- (IBAction)save:(id)sender {
    // save all table
    CGRect frame = self.tableView.frame;
    frame.size.height = self.tableView.contentSize.height;
    self.tableView.frame = frame;

    UIGraphicsBeginImageContextWithOptions(self.tableView.bounds.size, self.tableView.opaque, 0.0);
    [self.tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *saveImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    imageData = UIImagePNGRepresentation(saveImage);

    UIImage *image = [UIImage imageWithData:imageData];
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];


    [self createPDFfromUIView:imageView saveToDocumentsWithFileName:filename];
   }

- (NSMutableData*)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];
    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);
    return pdfData;
}

-(IBAction)back:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)email:(id)sender{

    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;


    UIImage *image = [UIImage imageWithData:imageData];
    UIImageView *imageView = [[UIImageView alloc]initWithImage:image];


    NSMutableData *pdfData = [self createPDFfromUIView:imageView saveToDocumentsWithFileName:filename];
    // Attach an image to the email
    [mc addAttachmentData:pdfData mimeType:@"application/pdf" fileName:filename];
    // Present mail view controller on screen
    [self presentViewController:mc animated:YES completion:NULL];

}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }

    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

我测试了imageData,捕获成功。 pdf 已生成,但它是单页。

期望的结果是捕获的图像imageData用于创建多页 pdf。

我应该如何调整“createPDFfromUIView”方法以使用 A4 标准纸张将长图像文件分成多个页面。

任何帮助将非常感激


尝试这个而不是UIGraphicsBeginImageContextWithOptions

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

        CGRect pdfPageBounds = CGRectMake(0, 0, 612, 792); // Change this as your need
       NSMutableData *pdfData = [[NSMutableData alloc] init];

       UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil); {
                        for (CGFloat pageOriginY = 0; pageOriginY < fittedSize.height; pageOriginY += pdfPageBounds.size.height) {
       UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil);

       CGContextSaveGState(UIGraphicsGetCurrentContext()); {
              CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0, -pageOriginY);
                                [self.tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
              } CGContextRestoreGState(UIGraphicsGetCurrentContext());
       }
      } UIGraphicsEndPDFContext();

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


// Use the pdfData to 
         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
         NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
                                filePathPDF = [documentsPath stringByAppendingPathComponent:@"image.pdf"]; //Add the file name
     BOOL written = [pdfData writeToFile:filePathPDF atomically:YES];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将整个表格视图捕获为图像,从中创建 .pdf 并通过电子邮件发送 的相关文章

  • 错误:“消息回复时间太长”向设备手表套件 OS 2 发送消息

    从 Apple Watch 向设备发送消息时出现以下错误 错误域 WCErrorDomain代码 7012 消息回复时间太长 UserInfo NSLocalizedDescription 消息回复时间太长 NSLocalizedFailu
  • 使用 pyobjc 将元数据写入 pdf

    我正在尝试使用以下 python 代码将元数据写入 pdf 文件 from Foundation import from Quartz import url NSURL fileURLWithPath test pdf pdfdoc PDF
  • SwiftUI TabbedView 仅显示第一个选项卡的内容

    我正在尝试建立一个TabbedView使用以下简单代码 TabbedView Text Hello world tabItemLabel Text Hello Text Foo bar tabItemLabel Text Foo 运行时 两
  • MKPolylineView initWithPolyLine:在 iOS 7 中已弃用

    我收到以下错误 initWithPolyline 已弃用 首先在 iOS 7 0 中弃用 MKPolylineView lineView MKPolylineView alloc initWithPolyline overlay 代替这个的
  • 一种简单、干净的方式来切换/交换视图?

    我已经看了几个来源 但我仍然很困惑 我想创建一个具有多个视图的应用程序 只有标准视图 没有表视图或其他任何内容 我可以在其中单击每个视图上的按钮来访问其他视图 我已经看到了多种方法来做到这一点 但对我来说唯一有意义的方法是让应用程序委托负责
  • UI键盘回避和自动布局

    鉴于 iOS 6 中对自动布局的关注以及 Apple 工程师的推荐 查看 WWDC 2012 视频 我们不再直接操作视图的框架 那么如何仅使用自动布局和 NSLayoutConstraint 来避免键盘呢 Update 这看起来是一个合理的
  • 在 ios wifi 网络上查找对等点

    我试图弄清楚如何搜索登录到 wifi 网络且在特定端口上托管应用程序的其他设备 在不知道这些其他设备的地址甚至不知道它们托管的端口的情况下 如何检测它们的存在 一旦发现 我应该能够联系该设备并与其建立连接 最标准的 iOS方式 是使用Bon
  • 块执行后变量返回 null

    我正在调度一个队列来在单独的线程上下载一些 flickr 照片 在 viewWillAppear 中 当我记录块内数组的内容时 它完美地显示了所有内容 dispatch queue t photoDowonload dispatch que
  • 目标操作 uicontrol 事件

    我一定在这里遗漏了一些明显的东西 但是 UIControl有一个方法 void addTarget id target action SEL action forControlEvents UIControlEvents controlEv
  • AWS MobileHub:重命名 Android / iOS 示例项目

    我是 AWS Mobilehub 的新手 我喜欢它允许我使用 AWS 配置选项创建项目 但是 当我尝试构建应用程序 ios swift android 时 它总是使用我的示例项目作为项目名称 在 AWS 项目的大多数配置设置中 例如使用 c
  • 在基于视图的 NSTableView 中,如何通过单击使控件成为第一响应者?

    基于视图的 NSTableView 似乎只有标准行为 为了使表内的文本字段成为第一响应者 用户必须双击或单击并 保持冷静 然而 考虑到基于视图的 NSTableViews 提供的灵活性 这种行为并不总是可取的 因为现在可能有很多不同且复杂的
  • 在 xCode 6 中发现意外的 Mach-O 标头代码:1918975009

    导致错误的原因是什么 Found an unexpected Mach O header code 1918975009 in xCode 6 我将我的项目存档并作为ad hoc构建并且它构建 链接 存档很好但是当我在xCode组织者和选择
  • UINavigationBar setBackgroundImage 在 AppDelegate 中使用 Swift

    我正在尝试在 Swift 的 App Delegate 中全局设置导航栏的背景图像 我可以让它在单独的视图控制器上工作 如下所示 var topBar UINavigationBar topBar setBackgroundImage UI
  • 如何将媒体附件添加到 iOS 10 应用程序中的推送通知中?

    有多个示例 您应该如何设置项目来添加使用 媒体附件 技术来显示图像的丰富通知 我已经阅读了其中的大部分内容 但我错过了一些内容 因为我的项目没有使用此有效负载显示任何丰富的通知 使用 APNS Tool 和 Boodle 进行测试 aps
  • AVPlayer 失败并显示 AVPlayerItemStatusFailed(OSStatus 错误 -12983)

    有时 AVPlayer 会失败AVPlayerItemStatusFailed发生故障后 AVPlayer 继续失败AVPlayerItemStatusFailed 我尝试清除 AVPlayer 实例并创建新实例 但无法实现AVPlayer
  • 如何修复此 YCrCb -> RBG 转换公式?

    我使用的公式来自这个问题 https stackoverflow com questions 8838481 kcvpixelformattype 420ypcbcr8biplanarfullrange frame to uiimage c
  • 在 Swift 中使用 Obj-C 完成块

    在 Objective C 中 我有一个完成块类定义为 File h typedef void MYCompletionBlock BOOL success NSDictionary result NSError error 然后 在 Sw
  • 如何使用回形针对多页 pdf 进行缩略图

    我想让 Paperclip 为上传的多页 PDF 文件的每一页创建 2 个缩略图 我正在运行 Paperclip 2 3 1 1 并在我的资产模型中使用它 has attached file asset styles gt medium g
  • 关闭应用程序后如何调试

    我正在尝试重现问题 这需要在特定位置关闭并重新打开我的应用程序 这是我的问题 1 如何查看我的日志 使用NSLog命令 当我的 iPhone 未连接到 XCode 时 2 是否可以将iPhone模拟器的特定位置 例如市中心 设置为默认位置
  • iOS 中的视频可以进行反卷积吗?

    我想拍摄击球手挥动棒球的镜头 但球棒很模糊 视频为 30 fps 通过研究 我发现反卷积似乎是最小化运动模糊的方法 但我不知道是否或如何在我的 iOS 应用程序后处理中实现它 我希望有人能给我指出正确的方向 比如如何在 iOS 中应用反卷积

随机推荐

  • XCode中文档下的“注释”的用途是什么

    字体选择框下方有一个自由文本字段Xcode 5 似乎属于Notes类别 那么 注释和空盒子的目的是什么under No Font如下图所示 我尝试为我的一个组件 即我的按钮 使用注释 并为其添加一些注释 如图 1 所示 这是 XIB 中按钮
  • 单个请求到多个异步响应

    所以 问题来了 iPhone 很棒 但对于有服务器端要求的应用程序来说 带宽和延迟是严重的问题 我解决这个问题的最初计划是对数据位发出多个请求 双关语无意 并以此来处理大量传入 传出数据的问题 由于很多原因 这是一个坏主意 对我来说最明显的
  • Selenium:如何拦截请求

    有人知道如何在 Selenium WebDriver 中拦截 获取请求 url XHR 和响应吗 是否可以 Webdriver 不直接支持它 但您可以通过代理重定向来捕获所有流量 在爪哇 Proxy proxy new Proxy This
  • StartsWith() 不会转换为 LINQ 中的 Like('abc%')

    我有以下 ASP NET Core LINQ 代码 List
  • 如何存储和更新具有不同数据类型属性的 localStorage 键对象?

    这是我第一次使用localStorage我想存储一个localStoragekey 是一个具有不同数据类型属性的对象 例如 key localstor 它是一个包含两个属性的对象 localstor userMsg String userI
  • 将 Excel 解析为 JSON

    我想知道是否可以将 excel 解析为 json 如果可能的话 Excel 的结构使其成为可能 有应用程序什么的吗 我有这个 JSON 结构http pastie org 2760828 http pastie org 2760828我必须
  • Swift 中的@dynamicCallable 是什么?

    来自苹果的文档 The dynamicCallable属性让你可以调用named types就像你打电话一样 使用简单语法糖的函数 主要用例是动态语言互操作性 你为什么要使用 dynamicCallable而不是直接方法 dynamicCa
  • Angular 7 - 向动态创建的组件添加拖放行为

    这是我在 SO 上提出的上一个问题的延续 在声明组件选择器时添加指令 Angular 7 https stackoverflow com questions 56072516 add directives to component sele
  • VBA-Loop 和一些工作表

    我是一个初学者 我想在我的 Excel 文件的所有工作表中进行循环 除了第一个工作表 然而 下面的代码仅适用于第二个 您能解释一下这段代码有什么问题吗 非常感谢 Sub MobileTCalculation MobileTCalculati
  • Ivy、Ant、Jenkins - 在 Jenkins 构建上使用 是个好主意吗?

    我们将使用 Ivy 和 Ant 并且让 Jenkins 来完成我们的构建 我原本以为让詹金斯做一个
  • 如何使用Nashorn引擎调用Java对象

    我想使用 Nashorn 控制台来替代 Rails c 例如 我想调用Java方法从远程系统导入数据并执行数据迁移 我发现这非常有趣 https www baeldung com java nashorn https www baeldun
  • 带或不带 MSYS 的 MinGW makefile(del 与 rm)

    我正在使用 MinGW 在 Windows 上编译一些东西 我打电话mingw32 make直接来自cmd exe一切 我需要的 都工作正常 但是我发现我需要能够从 MSYS 环境进行编译 并且我遇到了问题copy and del命令不被识
  • 触摸事件不适用于 Cordova 应用程序的 ios 版本

    我有一个非常简单的科尔多瓦应用程序 它是默认科尔多瓦 设备就绪 模板的扩展 它有一个按钮 附加了一个简单的单击事件 可以看到这里在 iOS 模拟器上运行 以下是我的项目的代码 索引 html
  • 使用记录编辑器/Jrecord 解压 COMP-3 数字

    我根据 cobol copybook 创建了布局 布局快照 我尝试加载数据并选择相同的布局 它给我的某些列提供了错误的结果 我尝试使用所有二进制数字类型 类阶边缘 DIV 无 EDG 办公室 无 EDG 注册区域无 EDG 城市 无 EDG
  • 使用“lapply”对数据框 (R) 中的所有列进行缩排序

    我正在尝试应用Winsorize 函数使用lapply来自library DescTools 包裹 我目前拥有的是 data col1 lt Winsorize data col1 这本质上用基于分位数的值替换了极值 替换了以下数据 gt
  • 在Python中解析日期字符串

    我如何重写以下子句 if u in date category title month 1 elif u in date category title month 2 elif u in date category title month
  • Firefox 和 Chrome 填充之间的区别

    Firefox 和 chrome 在 css 中渲染填充的方式有所不同 在 Chrome 中显示正确的内容在 Firefox 中进行了额外填充 有办法解决吗 button font family helvetica arial font s
  • ({"key": "value"} = {}) 语法在 JavaScript 函数中的含义是什么

    我正在学习 JavaScript 课程 特别是 MongoDB 大学 M220JS 课程 在其中一个任务中 我遇到了类内函数声明的语法 static async getMovies filters null page 0 moviesPer
  • Azure Functions 绑定重定向

    是否可以在 azure 函数文件夹结构中包含 web config 或 app config 文件以允许程序集绑定重定向 假设您正在使用最新的 2017 年 6 月 Visual Studio 2017 函数工具 我根据以下发布的代码片段得
  • 如何将整个表格视图捕获为图像,从中创建 .pdf 并通过电子邮件发送

    这是我第一次尝试在 iOS 中创建 pdf 文件 我有一个表格视图 它生成我想要在 pdf 文件中呈现的所有数据 这是我的代码 用于将整个表格捕获为图像 从图像生成 pdf 并通过电子邮件发送 IBAction save id sender