merging two pdfs in to single and attaching in the email in apex - salesforce

I have a requirement where I want to merge two pdfs in to a single pdf and attach in the attachements to the custom object in salesforce then this merged pdf is sent via email.
Here is my code snippet. Where contentPdf is one pdf and b is another pdf content which needs to be merged.
PageReference pdf = PageReference(/apex/FirstPDF?id='+ccId);
Blob contentPdf = pdf.getContent();
PageReference cadre = new PageReference('/apex/SecondPDF?id=' + ccId);
Blob b = cadre.getContentPdf();
String combinedPdf = EncodingUtil.convertToHex(contentPdf)+EncodingUtil.convertToHex(b);
Blob horodatagePdf = EncodingUtil.convertFromHex(combinedPdf);
Attachment attachment = new Attachment();
attachment.Body = horodatagePdf;
attachment.Name = String.valueOf('New pdf.pdf');
attachment.ParentId = ccId;
insert attachment;
But the problem is that it does not show the right documents merged instead it shows only one page in the final pdf saved in my machine. I have tried to use contentAsPdf() to retrieve content from pageReference but it does not work. Moreover the page is not well generated the one I get in the attachment. Or if there is any other way to do it quuickely.

I don't think you can merge PDF documents like that. It looks crazy. You can simply join text files together but anything more complex (JPEGs, PDFs...) has special structure... It's quite possible that your code works, in the sense that it generates a file which size is a sum of single files' sizes but it's not a valid document so only 1st part renders OK.
Try making another page which would just reuse the other 2 pages by calling them (use <apex:include>). Check if it renders close to what you're after (there might be style clashes for example) and if it's any good - call getContentAsPdf() on that?

Related

Send XLSX file as mail attachment via ABAP

I have to create an email and attach an XLSX file. I looked at the BCS_EXAMPLE_7 program.
I have transformed the content with the following method:
TRY.
cl_bcs_convert=>string_to_solix(
EXPORTING
iv_string = lv_content
iv_codepage = '4103'
iv_add_bom = 'X'
IMPORTING
et_solix = pt_binary_content
ev_size = pv_size ).
CATCH cx_bcs.
ls_return-type = text-023.
ls_return-message = text-024.
APPEND ls_return TO pt_return.
ENDTRY.
CONCATENATE lv_save_file_name '_' sy-datum '.xlsx' INTO lv_save_file_name.
lv_attachment_subject = lv_save_file_name.
CONCATENATE '&SO_FILENAME=' lv_attachment_subject INTO ls_attachment_header.
APPEND ls_attachment_header TO lt_attachment_header.
lo_document->add_attachment( i_attachment_type = 'XLS'
i_attachment_subject = lv_attachment_subject
i_attachment_size = pv_size
i_att_content_hex = pt_binary_content
i_attachment_header = lt_attachment_header ).
The email is sent correctly but when I open the attachment I see the error
Cannot open the file because the file extension is incorrect
Could you help me? thanks
That's a normal behavior of Excel, unrelated to ABAP, when the file name has extension .xlsx but doesn't contain data in format corresponding to XLSX. Excel does the same kind of checks for other extensions. If you need more information about these checks, please search the Web.
As I see that your program creates the attachment based on text converted into UTF-16LE code page (SAP code page 4103), I guess that you created the Excel data in format CSV, tab-separated values or even the old Excel XMLSS/XML 2003 format.
In that case, the extension .xlsx is not valid, to avoid the message, use the adequate extension, respectively .csv, .txt or .xml.
If you really need the extension .xlsx for some reason, then you must create the data in XLSX format. You may use the free API abap2xlsx. If you need further assistance about how to use abap2xlsx, please ask a new question (unrelated to email).
NB: maybe you were told to use the extension .xlsx although there is no real need to use it (each format has its own features, but simple unformatted values can be achieved with all formats), in that case you may propose to use a simple format like CSV or tab-separated values.
NB: you may also have the opposite case that Excel sniffs that the file contains data in format corresponding to XLSX, but the file name doesn't have the extension .xlsx, and the same for all other formats, but I can't say what is the exact Excel reaction to each case.
It appears that whatever you have in lv_content isn't actually a valid excel file. You can not just take arbitrary data, give it the extension .xlsx and expect MS Excel to know what to do with it.
Unfortunately, creating valid MS Office files is anything but trivial. It's a format which is theoretically open and based on XML (actually a zip archive containing multiple XML files), but in practice the specification is over a 5000(!) pages long.
Fortunately, there is a library for that. abap2xlsx is an open source (Apache License) library which provides an easy API to create (and read) valid XLSX files in ABAP.
You could also try to open the file with a text editor (eg. NotePad++), maybe this gives a hint of the actual content.
But I guess that something went wrong generating the binary table. Maybe you are using the wrong file size or code page.
Possible problems:
First problem: as correctly said by Sandra you may have invalid content of your lv_content variable, which doesn't correspond to correct XLSX structure.
Second problem: which you already solved, as seen from your coding, BCS classes do not support 4-character extensions.
Here is the sample how to build and send correct XLSX file via mail:
SELECT * UP TO 100 ROWS
FROM spfli
INTO TABLE #DATA(lt_spfli).
cl_salv_table=>factory( IMPORTING r_salv_table = DATA(lr_table)
CHANGING t_table = lt_spfli ).
DATA: lr_xldimension TYPE REF TO if_ixml_node,
lr_xlworksheet TYPE REF TO if_ixml_element.
DATA(lv_xlsx) = lr_table->to_xml( if_salv_bs_xml=>c_type_xlsx ).
DATA(lr_zip) = NEW cl_abap_zip( ).
lr_zip->load( lv_xlsx ).
lr_zip->get( EXPORTING name = 'xl/worksheets/sheet1.xml' IMPORTING content = DATA(lv_file) ).
DATA(lr_file) = NEW cl_xml_document( ).
lr_file->parse_xstring( lv_file ).
* Row elements are under SheetData
DATA(lr_xlnode) = lr_file->find_node( 'sheetData' ).
DATA(lr_xlrows) = lr_xlnode->get_children( ).
* Create new element in the XML file
lr_xlworksheet ?= lr_file->find_node( 'worksheet' ).
DATA(lr_xlsheetpr) = cl_ixml=>create( )->create_document( )->create_element( name = 'sheetPr' ).
DATA(lr_xloutlinepr) = cl_ixml=>create( )->create_document( )->create_element( name = 'outlinePr' ).
lr_xlsheetpr->if_ixml_node~append_child( lr_xloutlinepr ).
lr_xloutlinepr->set_attribute( name = 'summaryBelow' value = 'false' ).
lr_xldimension ?= lr_file->find_node( 'dimension' ).
lr_xlworksheet->if_ixml_node~insert_child( new_child = lr_xlsheetpr ref_child = lr_xldimension ).
* Create xstring and move it to XLSX
lr_file->render_2_xstring( IMPORTING stream = lv_file ).
lr_zip->delete( EXPORTING name = 'xl/worksheets/sheet1.xml' ).
lr_zip->add( EXPORTING name = 'xl/worksheets/sheet1.xml' content = lv_file ).
lv_xlsx = lr_zip->save( ).
DATA lv_size TYPE i.
DATA lt_bintab TYPE solix_tab.
* Convert to binary
CALL FUNCTION 'SCMS_XSTRING_TO_BINARY'
EXPORTING
buffer = lv_xlsx
IMPORTING
output_length = lv_size
TABLES
binary_tab = lt_bintab.
DATA main_text TYPE bcsy_text.
* create persistent send request
DATA(send_request) = cl_bcs=>create_persistent( ).
* create document object from internal table with text
APPEND 'Valid Excel file' TO main_text.
DATA(document) = cl_document_bcs=>create_document( i_type = 'RAW' i_text = main_text i_subject = 'Test Created for stella' ).
DATA lt_att_head TYPE soli_tab.
APPEND '<(>&< )>SO_FILENAME=MySheet.xlsx' TO lt_att_head.
* add the spread sheet as attachment to document object
document->add_attachment(
i_attachment_type = 'xls'
i_attachment_subject = 'MySheet'
i_attachment_size = CONV so_obj_len( lv_size )
i_attachment_header = lt_att_head
i_att_content_hex = lt_bintab ).
send_request->set_document( document ).
DATA(recipient) = cl_cam_address_bcs=>create_internet_address( 'some_recipient#mail.com' ).
send_request->add_recipient( recipient ).
DATA(sent_to_all) = send_request->send( i_with_error_screen = 'X' ).
COMMIT WORK.

Cannot create a Quote PDF with Apex when called from a Flow

I've created an InvocableMethod which is called from my Flow. This method simply creates a quote PDF and attaches it to the quote. This method looks like this:
#InvocableMethod(label='Create Quote PDF' description='Creates a PDF and saves it to the quote.')
public static void createPdf(List<string> quoteIds)
{
string quoteId = quoteIds[0];
//Create pdf content
PageReference pg = new PageReference('/quote/quoteTemplateDataViewer.apexp?id=xxx&summlid=yyy');
//Document object of quote which hold the quote pdf
QuoteDocument quotedoc = new QuoteDocument();
//Get the content of Pdf.
Blob b = pg.getContentAsPDF() ;
//content assign to document
quotedoc.Document = b;
//assign quote id where pdf should attach
quotedoc.QuoteId = 'xxx';
insert quotedoc;
}
This does not work when I execute my Flow; it will create a PDF and attach it to the quote but it will be blank. Funny thing is though, if I grab this code and execute in the anonymous window, it works fine! The PDF is generated as expected. It looks like it doesn't work if it's called from the Flow for some reason.
Any idea how I can fix this issue?

WPF find all regex matches in a xps document

I need to search an expression inside a xps document then list all matches (with the page number of each match).
I searched in google, but no reference or sample found which addresses this issue .
SO: How can I search a xps document and get this information?
The first thing to note is that an XPS file is an Open Packaging package. It can be opened and the contents accessed via the System.IO.Packaging.Package class. This makes any operations on the contents much easier.
Here's an example of how to search the page content with a given regex, while also tracking which page the match occurs on.
var regex = new Regex(#"th\w+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
using(var xps = System.IO.Packaging.Package.Open(#"C:\path\to\regex.oxps"))
{
var pages = xps.GetParts()
.Where (p => p.ContentType == "application/vnd.ms-package.xps-fixedpage+xml")
.ToList();
for (var i = 0; i < pages.Count; i++)
{
var page = pages[i];
using(var reader = new StreamReader(page.GetStream()))
{
var s = reader.ReadToEnd();
var matches = regex.Matches(s);
if (matches.Count > 0)
{
var matchText = matches
.Cast<Match>()
.Aggregate (new StringBuilder(), (agg, m) => agg.AppendFormat("{0} ", m.Value));
Console.WriteLine("Found matches on page {0}: {1}", i + 1, matchText);
}
}
}
}
It is not going to be as simple as you might have thought. XPS files are compressed (zipped) files containing a somewhat complex folder structure containing all the text, fonts, graphics and other items. You can use compression tools such as 7-Zip or WinZip etc. to extract the entire folder structure from an XPS file.
Having said that, you can use the following sequence of steps to do what you want:
Extract the contents of your XPS file programmatically in a temp folder. You can use the new ZipFile class for this purpose if you're using .NET 4.5 or better.
The extracted folder will have the following folder structure:
_rels
Documents
1
_rels
MetaData
Pages
_rels
Resources
Fonts
MetaData
Go to Documents\1\Pages\ subfolder. Here you'll find one or more .fpage files, one for each page of your document. These files are in XML format and contain all text contained in the page in a structured manner.
Use simple loop to iterate through all .fpage files, opening each of them using an XML reader such as XDocument or XmlDocument and search for required text in node values using RegEx.IsMatch(). If found, note down the page number in a List and move ahead.

Byte Array copy in Jsp

I am trying to append 2 images (as byte[] ) in GoogleAppEngine Java and then ask HttpResponseServlet to display it.
However, it does not seem like the second image is being appended.
Is there anything wrong with the snippet below?
...
resp.setContentType("image/jpeg");
byte[] allimages = new byte[1000000]; //1000kB in size
int destPos = 0;
for(Blob savedChart : savedCharts) {
byte[] imageData = savedChart.getBytes(); //imageData is 150k in size
System.arraycopy(imageData, 0, allimages, destPos, imageData.length);
destPos += imageData.length;
}
resp.getOutputStream().write(allimages);
return;
Regards
I would expect the browser/client to issue 2 separate requests for these images, and the servlet would supply each in turn.
You can't just concatenate images together (like most other data structures). What about headers etc.? At the moment you're providing 2 jpegs butted aainst one another and a browser won't handle that at all.
If you really require 2 images together, you're going to need some image processing library to do this for you (or perhaps, as noted, AWT). Check out the ImageIO library.
Seem that you have completely wrong concept about image file format and how they works in HTML.
In short, the arrays are copied very well without problem. But it is not the way how image works.
You will need to do AWT to combine images in Java

How to export Rich Text fields as HTML from Notes with LotusScript?

I'm working on a data migration task, where I have to export a somewhat large Lotus Notes application into a blogging platform. My first task was to export the articles from Lotus Notes into CSV files.
I created a Agent in LotusScript to export the data into CSV files. I use a modified version of this IBM DeveloperWorks forum post. And it basically does the job. But the contents of the Rich Text field is stripped of any formatting. And this is not what I want, I want the Rich Text field rendered as HTML.
The documentation for the GetItemValue method explicitly states that the text is rendered into plain text. So I began to research for something that would retrieve the HTML. I found the NotesMIMEEntity class and some sample code in the IBM article How To Access HTML in a Rich Text Field Using LotusScript.
But for the technique described in the above article to work, the Rich Text field need to have the property "Store Contents as HTML and MIME". And this is not the case with my Lotus Notes database. I tried to set the property on the fields in question, but it didn't do the trick.
Is it possible to use the NotesMIMEEntity and set the "Store Contents as HTML and MIME" property after the content has been added, to export the field rendered as HTML?
Or what are my options for exporting the Notes database Rich Text fields as HTML?
Bonus information: I'm using IBM Lotus Domino Designer version 8.5
There is this fairly unknown command that does exactly what you want: retrieve the URL using the command OpenField.
Example that converts only the Body-field:
http://SERVER/your%5Fdatabase%5Fpath.nsf/NEW%5FVIEW/docid/Body?OpenField
Here is how I did it, using the OpenField command, see D.Bugger's post above
Function GetHtmlFromField(doc As NotesDocument, fieldname As String) As String
Dim obj
Set obj = CreateObject("Microsoft.XMLHTTP")
obj.open "GET", "http://www.mydomain.dk/database.nsf/0/" + doc.Universalid + "/" + fieldname + "?openfield&charset=utf-8", False, "", ""
obj.send("")
Dim html As String
html = Trim$(obj.responseText)
GetHtmlFromField = html
End Function
I'd suggest looking at Midas' Rich Text LSX (http://www.geniisoft.com/showcase.nsf/MidasLSX)
I haven't used the personally, but I remember them from years ago being the best option for working with Rich Text. I'd bet it saves you a lot of headaches.
As for the NotesMIMEEntity class, I don't believe there is a way to convert RichText to MIME, only MIME to RichText (or retain the MIME within the document for emailing purposes).
If you upgrade to Notes Domino 8.5.1 then you can use the new ConvertToMIME method of the NotesDocument class. See the docs. This should do what you want.
Alternativly the easiest way to get the Domino server to render the RichText will be to actually retrieve it via a url call. Set up a simple form that just has the RichText field and then use your favourite HTTP api to pull in the page. It should then be pretty straight forward to pull out the body.
Keep it simple.
Change the BODY field to Store contents as HTML and MIME
Open the doc in editmode.
Save.
Close.
You can now use the NotesMIMEEntity to get what you need from script.
You can use the NotesDXLExporter class to export the Rich Text and use an XSLT to transform the output to what you need.
I know you mentioned using LotusScript, but if you don't mind writing a small Java agent (in the Notes client), this can be done fairly easily - and there is no need to modify the existing form design.
The basic idea is to have your Java code open a particular document through a localhost http request (which is simple in Java) and to have your code capture that html output and save it back to that document. You basically allow the Domino rendering engine to do the heavy lifting.
You would want do this:
Create a form which contains only the rich-text field you want to convert, and with Content Type of HTML
Create a view with a selection formula for all of the documents you want to convert, and with a form formula which computes to the new form
Create the Java agent which just walks your view, and for each document gets its docid, opens a URL in the form http://SERVER/your_database_path.nsf/NEW_VIEW/docid?openDocument, grabs the http response and saves it.
I put up some sample code in a similar SO post here:
How to convert text and rich text fields in a document to html using lotusscript?
Works in Domino 10 (have not tested with 9)
HTMLStrings$ = NotesRichTextItem .Converttohtml([options] ) As String
See documentation :
https://help.hcltechsw.com/dom_designer/10.0.1/basic/H_CONVERTOHTML_METHOD_NOTESRICHTEXTITEM.html
UPDATE (2022)
HCL no longer support this method since version 11. The documentation does not include any info about the method.
I have made some tests and it still works in v12 but HCL recommended to not use it.
Casper's recommendation above works well, but make sure the ACL is such to allow Anonymous Access otherwise your HTML will be the HTML from your login form
If you do not need to get the Richtext from the items specifically, you can use ?OpenDocument, which is documented (at least) here: https://www.ibm.com/developerworks/lotus/library/ls-Domino_URL_cheat_sheet/
https://www.ibm.com/support/knowledgecenter/SSVRGU_9.0.1/com.ibm.designer.domino.main.doc/H_ABOUT_URL_COMMANDS_FOR_OPENING_DOCUMENTS_BY_KEY.html
OpenDocument also allows you to expand sections (I am unsure if OpenField does)
Syntax is:
http://Host/Database/View/DocumentUniversalID?OpenDocument
But be sure to include the charset parameter as well - Japanese documents were unreadable without specifying utf-8 as the charset.
Here is the method I use that takes a NotesDocument and returns the HTML for the doc as a string.
private string ConvertDocumentToHml(Domino.NotesDocument doc, string sectionList = null)
{
var server = doc.ParentDatabase.Server.Split('/')[0];
var dbPath = doc.ParentDatabase.FilePath;
string viewName = "0";
string documentId = doc.UniversalID.ToUpper();
var ub = new UriBuilder();
ub.Host = server;
ub.Path = dbPath.Replace("\\", "/") + "/" + viewName + "/" + documentId;
if (string.IsNullOrEmpty(sectionList))
{
ub.Query = "OpenDocument&charset=utf-8";
}
else
{
ub.Query = "OpenDocument&charset=utf-8&ExpandSection=" + sectionList;
}
var url = ub.ToString();
var req = HttpWebRequest.CreateHttp(url);
try
{
var resp = req.GetResponse();
string respText = null;
using (var sr = new StreamReader(resp.GetResponseStream()))
{
respText = sr.ReadToEnd();
}
return respText;
}
catch (WebException ex)
{
return "";
}
}

Resources