Microsoft Power Platform: Converting HTML to PDF in Power Automate using PDFShift API

January 11, 2021 4 comments

Recently I worked on PDFShift for converting HTML to PDF with header and footer. I checked if we have any article which will explain how to use PDFShift API to convert HTML to CSS, but I do not find any article on this. Hence, I tried myself and made it through.

We have some other service provider for PDF conversion API’s which are already available in form of connection in Microsoft 365, example Muhimbi, Plumsail and others. So, after your evaluation of cost and features, if you have chosen PDFShift then you can use this article.

This article will explain you how we can call PDFShift API to convert the list item data in PDF and send the pdf as email.

PDFShift provides API to convert html to pdf, multiple features are provided with PDFShift. You can check more details and pricing details at https://pdfshift.io/#pricing

Some of the important feature of PDFShift like following –

Parallel conversions – Process multiple documents in parallel to increase conversion speed.

Asynchronous request – Use our powerful webhook system to be notified once a conversion is done.

Advanced Options – Set custom headers and footers with pagination, inject custom CSS and JavaScript, encrypt your documents and many more!

Raw HTML support – No need to make your private page public. Simply send us your raw HTML data instead and we will convert it.

High-Fidelity PDF – Generate a high-fidelity document, close to your original HTML, in a few seconds.

Privacy-focused – That’s why your documents are not stored on our server (except when explicitly requested) and are not kept for more than 2 days.

Asynchronous request feature is most important feature in real life sacnorao.

I tried to search any readily available connector for PDFShift, but do not found one.

I have created a sample SharePoint list with name as “Temp” with following columns –

Temp list columns and data
Temp list columns and data

Created a flow with item created. Selected my SharePoint list and added Get item activity to get the newly created item. You can change it according to your requirement and according to suitable event for your requirement.

Trigger workflow on item created
Trigger workflow on item created

After this getting the list item, we can create a HTML for that item. I used following formula to get the HTML for list item in Value

concat(‘<html><body><table border=”1px”><tr><th>Title</th><th>Name</th><th>Address</th></tr><tr><td>’,outputs(‘Get_item’)?[‘body/Title’],'</td><td>’,outputs(‘Get_item’)?[‘body/Name’],'</td><td>’,outputs(‘Get_item’)?[‘body/Address’],'</td></tr></table></body></html>’)

Initialize variable for HTML string
Initialize variable for HTML string

Once we get the HTML for list item, we used the HTTP action to call the PDFShift convert API. As PDFShift uses basic authentication, we used basic authentication in HTTP action to authenticate.

You need to provide the API key you get in the “Password” field and in “UserName” field pass value api

HTTP trigger action
HTTP trigger action

Now, we need to create a Variable of type “Object” to collect the output of the HTTP action.

In the next step create an “Array” type variable to create the Attachment array to be send with email.  

Initialize variable Object and Array type
Initialize variable Object and Array type

After creating Array variable, we need to assign the value which we get from HTTP call.

For attachment name let’s use the formula as following –

concat(outputs(‘Get_item’)?[‘body/Name’],’.pdf’)

For PDF content let’s get the value from ‘’PDFOutput’ variable, like following –

variables(‘PDFOutput’)[‘$content’]

Append to array variable
Append to array variable

After creating the array variable, we need to pass the array variable for Send email action.

Send an email (V2) action
Send an email (V2) action

Let’s pass the Attachment array variable in the ‘Send an email (V2)’ action like following.

Send an email (V2) with attachment
Send an email (V2) with attachment

The complete flow will look like following –

Entire Flow
Entire Flow

After creating a new item in the list ‘Temp’, our flow will get triggered and you will get the generated PDF attached in your inbox like following –

Email received in Inbox
Email received in Inbox

Converted PDF in email attachment will look like following –

Received pdf in email
Received pdf in email

If we explore the value of HTTP action and check the value of ‘PDFOutput’ variable, you will found the value like following where $content gives you PDF content in Base64 format.

Response From PDFShift with HTTP call
Response From PDFShift with HTTP call

You can use this approach in many application , for example insurance kind of application where details get filled from a Power app and gets stored in the SharePoint list, so as proof of the proposal the selected options get converted into PDF and stored in the SharePoint list as well as sent as an email.

Some more scenarios can be addressed similar ways.

You can add HEADER and FOOTER to PDF as well while calling the convert API, you can explore more options at PDFShift documentation at https://docs.pdfshift.io/

Some important points to consider –

  1. HTTP Request action is a premium action and require premium licensing.
  2. PDFShift service is also paid service, you can visit their site for more details.

I have attached the exported flow Download and rename it to .zip

In upcoming blog, I will explain the real world monitoring sacnorao using the PDFShift and Power Automate to monitor the usage of the API.

SharePoint online: Error ‘Updates are currently disallowed on GET requests. To allow updates on a GET, set the ‘AllowUnsafeUpdates’ property on SPWeb’ while creating new app catalog site

July 6, 2020 2 comments

Recently I have created new E5 personal tenant for my development and testing purpose. I wanted to deploy and test the SPFx component in that tenant, hence I tried to create the App catalog.

I directly went to SharePoint admin center in Office 365 and tried to create new App catalog site, like following.

App catalog Creation

App catalog Creation

I got the error ‘Updates are currently disallowed on GET requests. To allow updates on a GET, set the ‘AllowUnsafeUpdates’ property on SPWeb’.

App catalog Creation Error

App catalog Creation Error

I initially thought that the error is due to some technical glitch and no clear reason of the error explained in error and hence I tried to create App catalog site couple of times more but no luck and got the same error.

The solution is bit weird as I just created new tenant, I do not have any site created yet and I jumped directly to create app catalog site.

Then I have created one test site in tenant.

One Site Created

One Site Created

And it worked, I again tried creating the App catalog site and it worked.

App Catalog Success

App Catalog Success

So we need to at least create one site before creating App catalog. The only concern is Microsoft should provide some meaningful error message so that we will not be confused.

Sharing is caring, stay safe. Take care.

Visual studio load test giving error- Request failed: The request was aborted: Could not create SSL/TLS secure channel

November 29, 2019 Leave a comment

Recently I ran the load tests in visual studio, I got errors “Request failed: The request was aborted: Could not create SSL/TLS secure channel”. Those load tests are working fine previously but suddenly stopped working. After investigation I found that recently our production server had some changes in TLS protocol support and now TLS 1.2 support added.

Request failed: The request was aborted: Could not create SSL/TLS secure channel.

Request failed: The request was aborted: Could not create SSL/TLS secure channel.

So, the cause found is recent change done on server but now finding the solution to resolve this issue and run the load test in visual studio.

Solutions:

We need to create Web Performance Test Plug-In to resolve this issue.

  1. Open a Web performance and load test project that contains a Web load test.
  2. In Solution Explorer, right-click on the solution and select Add and then choose New Project.The Add New Project dialog box is displayed.
  3. Under Installed Templates, select Visual C#.
  4. In the list of templates, select Class Library.
  5. In the Name text box, type a name for your class. Choose OK.
    Visual studio add new class library project
    Visual studio add new class library project
  6. The new class library project is added to Solution Explorer and the new class appears in the Code Editor.
  7. In Solution Explorer, right-click the References folder in the new class library and select Add Reference.
  8. The Add Reference dialog box is displayed.
  9. Choose the .NET tab, scroll down, and select Microsoft.VisualStudio.QualityTools.WebTestFramework. Choose OK.
  10. The reference to Microsoft.VisualStudio.QualityTools.WebTestFramework is added to the Reference folder in Solution Explorer.
    Visual studio add reference
    Visual studio add reference
  11. In Solution Explorer, right-click on the top node of the Web performance and load test project that contains the load test to which you want to add the Web performance test plug-in and select Add Reference.
  12. The Add Reference dialog box is displayed. Choose the Projects tab and select the Class Library Project. Choose OK.
    Visual studio add plugin project reference
    Visual studio add plugin project reference
  13. In the Code Editor, write the code of your plug-in. First, create a new public class that derives from WebTestPlugin.
  14. Implement code inside one or more of the event handlers.
  15.          public class Tls12ForcedPlugin : WebTestPlugin
        {
            [Description("Enable or Disable the plugin functionality")]
            [DefaultValue(true)]
            public bool Enabled { get; set; }
    
            public override void PreWebTest(object sender, PreWebTestEventArgs e)
            {
                base.PreWebTest(sender, e);
                
                // We're using SSL2 here and not TLS. Without this line, nothing works.
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc00);// SecurityProtocolType.Ssl2;
    
                //we wire up the callback so we can override  behavior and force it to accept the cert
                ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCB;
    
                //let them know we made changes to the service point manager
                e.WebTest.AddCommentToResult(this.ToString() + " PP has made the following modification-> ServicePointManager.SecurityProtocol set to use SSLv3 in WebTest Plugin.");
            }
            public static bool RemoteCertificateValidationCB(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                //If it is really important, validate the certificate issuer here.
                //this will accept any certificate
                return true;
            }
    }
            
  16. If you are using Framework 4.0 then you may get error SecurityProtocolType.Ssl2 not found.For other Framework –

    SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12

    For Framework 4.0

    (SecurityProtocolType)(0xc0 | 0x300 | 0xc00)

  17. After you have written the code, build the new project.
  18. Open a Web performance test. To add the Web performance test plug-in, choose Add Web Test Plug-in on the toolbar.
  19. The Add Web Test Plug-in dialog box is displayed. Under Select a plug-in, select your Web performance test plug-in class.
  20. Visual studio plugin project displayed

    Visual studio plugin project displayed

  21. In the Properties for selected plug-in pane, set the initial values for the plug-in to use at run time. Choose OK.
    Visual studio error resolved
    Visual studio error resolved

Step by step installation of SharePoint Server 2019 preview for single server farm topology

Hi Friends,

As we know that SharePoint Server 2019 and Project Server 2019 preview available, I was excited with this news and thought to have it installed on and check what’s now.
Following article will have instructions to install SharePoint Server 2019 preview on Azure VM.
Let’s start by creating the virtual machine on Windows Azure platform.
I have created a VM with image template ‘SQL Server 2017 Standard on Windows Server 2016’.

SP2019_Azure VM Image

I have chosen ‘Standard B4Ms’ sizes configuration.

SP2019_Azure VM

And created the VM, it have taken some time to get it created. Following are the configuration shown on the created VM on Azure.

Now as we have Virtual machine ready with SQL server 2017, we can start with SharePoint Server 2019 installation.
1. Let’s first download the setup from https://www.microsoft.com/en-us/download/details.aspx?id=57169
2. I have chosen ‘en-us\16.0.10711.37301_OfficeServer_none_ship_x64_en-us_dvd\officeserver_en-us.img’ installation language for downloading installation, its 3.8GB size.

Download SharePoint Server

3. Click Save to copy the disc image file to your computer.
4. Right click on the ‘officeserver_en-us.img’ file and select Mount option.

Mount_Image

5. Navigate to the mounted drive.
6. Run splash.hta to launch the SharePoint Server 2019 Start page.
7. Click Install software prerequisites to launch the Microsoft SharePoint 2019 Products Preparation Tool.

SP2019_1

8. Follow the instructions in the tool to complete the installation of the software prerequisites.

SP2019_2

9. Select ‘Finish’ to restart the server and complete the installation of prerequisites.
10. After restart if the image file not mounted automatically then repeat step 4,5 and 6 to run the splash.hta file.
11. On the SharePoint Server 2019 Start page, click ‘Install SharePoint Server’ to launch Microsoft SharePoint Server 2019 Public Preview Setup.

SP2019_3

12. When prompted, provide a product key. You can use the trial product key from article install instructions section. The trial period is 180 days. You can convert to a licensed installation at any time during the trial or after the trial has expired by entering the appropriate product key in Central Administration.

SP2019_4

13. Sit back and relax to complete the installation.

SP2019_5

SP2019_6

14. After completing the setup SharePoint Product configuration wizard will be started.

SP2019_7

15. Select ‘Yes’ at the following screen.

SP2019_8

16. As we are creating new farm, select as below screen shot.

SP2019_9

17. Select Next on below screen.

SP2019_16

18. In next screen we need to provide DB server details and Database access account details.

SP2019_11

19. After giving user details using which we have created the VM,I was getting following error “The specified user is a local account. Local accounts should only be used in stand alone mode.

SP2019_12

20. I thought we need to create a SQL user and pass that to continue the setup.
21. Hence I connected to SQL server management studio.

SP2019_13

22. I have created a new SQL user.

SP2019_14

23. And granted all the roles to that account.

SP2019_15

24. Now selected the newly created user also not helping me and giving same error as given in step no 19.
25. After that I have tried creating the new local user account and added that to Local administrator group and using those user in SQL. This also not helped me and I got stuck for some time.
26. After searching for the error we came across SP 2016 post when the solution was described to use the New-SPConfigurationDatabase cmdlet.

 

New-SPConfigurationDatabase -DatabaseName SharePoint_ConfigDB -DatabaseServer [ServerName] -AdministrationContentDatabaseName SharePoint_ContentDB -Passphrase (ConvertTo-SecureString [password] -AsPlaintext -Force) -FarmCredentials (Get-Credential) -localserverrole SingleServerFarm

27. Please read about at cmdlet New-SPConfigurationDatabase , I used ‘SingleServerFarm’ option for localserverrole parameter as I am installing on single server.
28. This command will take some time and create configuration database.
29. After successful completion run the SharePoint product configuration wizard again.

SP2019_16

30. This time it got succeed and we are able to proceed.

SP2019_17

31. Click Next to continue with configuration. And wizard will continue as following.

SP2019_18

SP2019_19

32. Now the final configuration task started and installation continued.

SP2019_20

33. Installation success message shown as following.

SP2019_21

34. Now we can able to access SharePoint central administration.

SP2019_22

We can now free to create web application and site collection. Modern site templates are available at ‘Template selection’ step.

Hope this article will help to save some valuable time while setting up SharePoint 2019 preview.
Thanks for Reading.

SharePoint online / SharePoint 2013: Sharing variable values between search control and display templates

November 29, 2017 Leave a comment

Recently I came across to a scenario where I need to set the variable in control template and the value of the variable should be accessible in item template and vice versa.
I was showing some data in item templates and using third party pagination for displaying the search result, needed the value of pagination size which is available in control template.
I tried with normal JavaScript variable but due to the scoping in display template it was not available for me inside the item template.
Solution 1:
We can use Windows.variable which is nothing but global variable creation on the scope of the window object and hence will be accessible throughout the scope of windows object.
Control Template:

<!--#_ window.PageSize = "30"; _#-->

Item Template:

<!--#_ alert(window.PageSize); _#-->

Solution 2:
Another better alternative is to use the built-in ctx object which is already shared between the control and item display template.
Control Template:

<!--#_ ctx.PageSize = "30"; _#-->

Item Template:

<!--#_ alert(ctx.PageSize); _#-->

Happy learning.

SharePoint 2013: Creating and calling custom JavaScript function in search display template

October 23, 2017 Leave a comment

Hi Friends,

Recently I came across a requirement where I need to create a custom JavaScript function which will change the date formatting on the provided string date parameter.

I tried creating normal JavaScript function in display template and tried calling it from other part of template but the function was undefined and not found inside the display template, I got little bit confused as I have created the JavaScript function in same display template but still not able to find it in same display template while calling. We can have couple of ways to resolve the issue.

Solution 1:

After some googling I found the cause of the issue and the solution as well, as follows.

The possible reason is scoping of the display template not allowing to consider external JavaScript function as a part of the scope to call inside display template.

The solution is to create new function on window scope and the call it in the desired place inside display template.

window.MyTestFunction = function(myParam)
{
// your own logic to work on the param 'myParam'
}

Calling the function:

<a style="cursor:pointer" onclick='window.MyTestFunction(3)'>Call My custom JS function</a>

Solution 2:

  1. Create a JavaScript file (MySampleJS.js) in the Display Templates/Search folder.
  2. Add the custom JS function in to the MySampleJS.js file.
  3. Add the following code into thetag below to include the JS file in display template
<script>
$includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Search/ MySampleJS.js");
</script>

Happy learning.

SharePoint 2013: Converting GMT/UTC time to local time in XSLT for rendering RSS feed

September 28, 2017 Leave a comment

Hi Friends,

Recently I came across the requirement where the date coming from RSS feed which is in GMT format needed to be converted to local time and display in required format.

As RSSAggregatorWebPart webparts executes on server side and renders the output html in browser, we cannot utilize the rss date to convert to local date.

I tried multiple solution with default XSLT for calling JavaScript function, like CDATA, xsl:comment and try adding script tag but none worked for me.

Finally after struggling I found a way to achieve desired result using onerror handler with img tag.

Solution as fallows –

XSLT changes

Add following section in XSLT, which actually uses the img tag to call the JavaScript function using on error event.

Rss1

JavaScript changes

Following function we needed to add a separate JS file which will be referred in the master page or add in master page itself and make sure it that JS method gets loaded before the method call in XSLT.

function ConverDateToLocal(pDate, sender) {
    try {
        var today = new Date(pDate);
        var dd = today.getDate();
        var mm = today.getMonth() + 1; //January is 0!
        var yyyy = today.getFullYear();
        var hh = today.getHours();
        var mmm = today.getMinutes();
        /*if(dd<10) {
            dd='0'+dd
        } 

        if(mm<10) {
            mm='0'+mm
        } */
        var restStr = dd + '.' + mm + '.' + yyyy + " " + hh + ":" + mmm;
        if (sender != null) {
        var senderid = sender.id;
        if (senderid) {
        var senderidsplit = senderid.split('_');
        if (senderidsplit.length > 0) {
                    var datedivid = "datediv_" + senderidsplit[1];
                    if (datedivid) {
                        var datediv = document.getElementById(datedivid);
                        if (datediv != null) {
                            datediv.innerHTML += " :: " + "New ::" + restStr;
			                // After testing folling code should be execuated
			                //datediv.innerHTML = restStr;
                        }
                    }
                }
            }
        }
    }
    catch(err) {}
}

After applying the XSLT we can see the output like following where first date is GST date and next date is converted local date.

RSS3

Happy coding.

SharePoint: How to check if page is in edit mode or not in JavaScript

August 28, 2017 Leave a comment

As SharePoint evolved and other client technologies started to become popular and independent we are achieving most of the solution with client side technologies like JavaScript, jQuery and other similar.

I came across one requirement while working on a JavaScript based component, where I need a conditional code to run only when my page is in edit mode. I found multiple solutions which I summaries below.

Option 1:

var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
if (inDesignMode == "1")
{
// page is in edit mode
}
else
{
// page is in browse mode
}

For Wiki pages

var wikiInEditMode = document.forms[MSOWebPartPageFormName]._wikiPageMode.value;
if (wikiInEditMode == "Edit")
{
// wiki page is in edit mode
}
else
{
// wiki page is not in edit mode
}

Option 2: Using SP.Ribbon.PageState.Handlers.isInEditMode()

ExecuteOrDelayUntilScriptLoaded(function(){
var InEditMode = SP.Ribbon.PageState.Handlers.isInEditMode();
if(InEditMode){
// page is in edit mode
}
}, 'SP.Ribbon.js');

Option 3: While checking the value in SharePoint search display template we need to use Srch.U.isPageInEditMode Method

var isRollupPageInDisplayMode = Srch.ContentBySearch.isRollupPage(ctx.ClientControl) && !Srch.U.isPageInEditMode();

Happy Learning!