zoukankan      html  css  js  c++  java
  • Salesforce: getContent()和getContentAsPDF()的使用

    需求中,需要将VF页面的内容转换成Blob格式使用,即会用到getContent()或者getContentAsPDF()方法

    首先要将VF页面进行实例化:

    PageReference invoicePage = new PageReference('/apex/KayakInvoicePDF');
     
    还可以给VF页面传递参数:
    invoicePage.getParameters().put('id', invoice.Id);
     
    然后即可使用getContent()或者getContentAsPDF()将页面转换为blob格式:
    Blob pageData = invoicePage.getContent();
    Blob pageData = invoicePage.getContentAsPDF();
     
    getContent(): 返回的Blob的内容取决于页面的呈现方式。如果页面以PDF文件呈现,它将返回PDF文档。如果页面未呈现为PDF,它将返回HTML。要以string形式访问返回的HTML的内容,可以使用toString()方法。
    getContentAsPDF(): 返回的Blob内容始终以PDF格式呈现。
     
    要注意的是getContent()和getContentAsPDF()都不能在这三种情况下使用:
    Triggers
    Test methods
    Apex email services
     
    转化为Blob之后,即可将它应用到实际情况中。
     
    附参考代码:
    PageReference invoicePage = new PageReference('/apex/KayakInvoicePDF');
    invoicePage.getParameters().put('id', recordId);
    invoicePage.setRedirect(false);
    Blob pageData;
    if (!Test.isRunningTest()) {
      pageData = invoicePage.getContent();
      //pageData = invoicePage.getContentAsPDF();
    } else {
      pageData = Blob.valueOf('this is a test');
    }
     
    //create attachment
    Attachment att = new Attachment(ParentId = recordId, Body = pageData, Name='Test.pdf');
    insert att;
     
    //create and send email
    Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
    attachment.setBody(pageData);
    attachment.setContentType('application/pdf');
    attachment.setFileName('attachment.pdf');
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setSubject('Test Email');
    mail.setToAddresses(new String[]{ 'test@test.com' });
    mail.setHtmlBody('test');
    mail.setFileAttachments(new Messaging.EmailFileAttachment[]{ attachment });
    Messaging.sendEmail(new Messaging.Email[]{ mail }, false);
     
  • 相关阅读:
    sqlserver 中数据类型bit的使用 Followyour
    如何在保证睡眠的情况把各种事情做好
    求职具备八大素质
    提高效率的5条黄金法则
    随笔摘录:世上只有一件东西,能始终经受住生活的冲击:一颗宁静的心。
    Hadoop中文文档 (0.19.0)
    两个微型的Map/Reduce框架: FileMap(FM)和BashReduce
    Hadoop的商业化支持
    Yahoo的Hadoop版本
    Map/Reduce and Queues for MySQL Using Gearman
  • 原文地址:https://www.cnblogs.com/clsriz/p/13558375.html
Copyright © 2011-2022 走看看