Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, February 23, 2017

Map WFFM Form fields in tabular format in PDF file



In one of our requirement, we have to save WFFM form fields data in PDF file so that WFFM fields data showed in tabular format.
 
I created WFFM form and created a new Save action under “/sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Save Actions

My WFFM form looks as

Sample WFFM Form
Sample WFFM Form


I bind the newly created Save action to this WFFM form.

I am using iTextSharp to generate PDF file.

Here is the code for this Save Action.

using System;
using System.Linq;
using Sitecore.Data;
using Sitecore.WFFM.Abstractions.Actions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace SitecorePOCinMVC.Web
{
    public class MyCustomAction : ISaveAction
    {
        public ID ActionID { get; set; }
        public string UniqueKey { get; set; }
        public ActionType ActionType { get; private set; }
        public ActionState QueryState(ActionQueryContext queryContext)
        {
            return ActionState.Enabled;
        }

        public void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data)
        {
            try
            {
                GeneratePDFFile(adaptedFields);
            }
            catch (Exception ex)
            {
                System.IO.File.AppendAllText("d:\\sitecoretext.txt", "PDF Error : -" + ex.Message);
            }
        }

        private void GeneratePDFFile(AdaptedResultList adaptedFields)
        {
            //Create document
            Document doc = new Document();

            //Create PDF Table
            PdfPTable tableLayout = new PdfPTable(4);

            //Create a PDF file in specific path
            PdfWriter.GetInstance(doc, new FileStream(@"D:\Sample-PDF-File.pdf", FileMode.Create));

            //Open the PDF document
            doc.Open();

            //Add Content to PDF
            doc.Add(AddContentToPDF(tableLayout, adaptedFields));

            // Closing the document
            doc.Close();

        }

        private PdfPTable AddContentToPDF(PdfPTable tableLayout, AdaptedResultList adaptedFields)
        {
            float[] headers = { 40, 40, 0, 0 };  //Header Widths
            tableLayout.SetWidths(headers);        //Set the pdf headers
            tableLayout.WidthPercentage = 80;       //Set the PDF File witdh percentage

            //Add Title to the PDF file at the top
            tableLayout.AddCell(new PdfPCell(new Phrase("WFFM Generated Document", new Font(Font.NORMAL, 13, 1, new iTextSharp.text.BaseColor(153, 51, 0)))) { Colspan = 4, Border = 0, PaddingBottom = 20, HorizontalAlignment = Element.ALIGN_CENTER });

            //Add header
            AddCellToHeader(tableLayout, "Fields Name");
            AddCellToHeader(tableLayout, "User entered data");
            tableLayout.CompleteRow();

            foreach (var i in adaptedFields.ToList())
            {
                AddCellToBody(tableLayout, i.FieldName);
                AddCellToBody(tableLayout, i.Value);
                tableLayout.CompleteRow();
            }

            return tableLayout;
        }

        /// <summary>
        /// Method to add single cell to the header
        /// </summary>
        /// <param name="tableLayout"></param>
        /// <param name="cellText"></param>
        private static void AddCellToHeader(PdfPTable tableLayout, string cellText)
        {
            tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.NORMAL, 8, 1, iTextSharp.text.BaseColor.WHITE))) { HorizontalAlignment = Element.ALIGN_CENTER, Padding = 5, BackgroundColor = new iTextSharp.text.BaseColor(0, 51, 102) });
        }

        /// <summary>
        /// Method to add single cell to the body
        /// </summary>
        /// <param name="tableLayout"></param>
        /// <param name="cellText"></param>
        private static void AddCellToBody(PdfPTable tableLayout, string cellText)
        {
            tableLayout.AddCell(new PdfPCell(new Phrase(cellText, new Font(Font.NORMAL, 8, 1, iTextSharp.text.BaseColor.BLACK))) { HorizontalAlignment = Element.ALIGN_CENTER, Padding = 5, BackgroundColor = iTextSharp.text.BaseColor.WHITE });
        }
    }
}

After executing this code, I can generate PDF file and able to save WFFM fields data in tabular format as

WFFM Generated PDF
WFFM Generated PDF

I hope you like this Sitecore tip. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)

Please leave your comments or share this tip if it’s useful for you.

Post WFFM form if submit button is hidden



Once you hide WFFM form Submit button, then how to call its Submit action on click of MVC form Submit button.

Below java script done the magic for this

if ($(".form-submit-border").length > 0) {
   $(".form-submit-border > .btn").trigger('click');
}

Here is the complete code for scenario

HTML in View

<button class="submit" id="product-create-button" onclick="return CreateProduct();" type="submit">Submit</button>

Javascript

function CreateProduct() {

        var param = {
            productItemId: $("#product-select").val(),
            quality: $("#quality-select").val(),
        };

        $.ajax({
            dataType: 'json',
            type: 'POST',
            async: false,
            url: _rootUrl + '/product/create',
            data: param,
            success: function (result) {
                if ($(".form-submit-border").length > 0) {
                    $(".form-submit-border > .btn").trigger('click');
                }
            },
            error: function (response, ajaxOptions, thrownError) {
                alert('Error');
            }
        });
    return false;
}

I am calling Javascript method on click of MVC form Submit button. Its send the required data to Controller action method via AJAX call. On success of AJAX operation, I am triggering click event of WFFM form Submit button which eventually call WFFM Execute action.

I hope you like this Sitecore tip. Stay tuned for more Sitecore related articles.

Till that happy Sitecoring :)


Please leave your comments or share this tip if it’s useful for you.