working on it ...

Filters

Explore Public Snippets

Sort by

Found 4,735 snippets matching: merge

    public by sherazam  228330  0  5  0

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps

    How to Insert Check Boxes or HTML into Word Docs during Mail Merge inside .NET Apps
    // Enter here the actual content of the snippet.            
    //[C# Code Sample]
     
    using System;
    using System.IO;
    using System.Reflection;
    using Aspose.Words;
    using Aspose.Words.Fields;
    using Aspose.Words.MailMerging;
    
    namespace MailMergeFormFields
    {
        /// <summary>
        /// This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        /// </summary>
        class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            public static void Main(string[] args)
            {
                Program program = new Program();
                program.Execute();
            }
    
            private void Execute()
            {
                string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
                string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;
    
                // Load the template document.
                Document doc = new Document(dataDir + "Template.doc");
    
                // Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = new HandleMergeField();
    
                // This is the data for mail merge.
                String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
                    "Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
                Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
                    "<b>HTML Body Test message 1</b>", true, false, true};
    
                // Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues);
    
                // Save the finished document.
                doc.Save(dataDir + "Template Out.doc");
            }
    
            private class HandleMergeField : IFieldMergingCallback
            {
                /// <summary>
                /// This handler is called for every mail merge field found in the document,
                ///  for every record found in the data source.
                /// </summary>
                void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
                {
                    if (mBuilder == null)
                        mBuilder = new DocumentBuilder(e.Document);
    
                    // We decided that we want all boolean values to be output as check box form fields.
                    if (e.FieldValue is bool)
                    {
                        // Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName);
    
                        // It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
    
                        // Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0);
    
                        // Nothing else to do for this field.
                        return;
                    }
    
                    // We want to insert html during mail merge.
                    if (e.FieldName == "Body")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        mBuilder.InsertHtml((string)e.FieldValue);
                    }
    
                    // Another example, we want the Subject field to come out as text input form field.
                    if (e.FieldName == "Subject")
                    {
                        mBuilder.MoveToMergeField(e.FieldName);
                        string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex);
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0);
                    }
                }
    
                void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
                {
                    // Do nothing.
                }
    
                private DocumentBuilder mBuilder;
            }
        }
    }
     
    //[VB.NET Code Sample]
     
    
    Imports Microsoft.VisualBasic
    Imports System
    Imports System.IO
    Imports System.Reflection
    Imports Aspose.Words
    Imports Aspose.Words.Fields
    Imports Aspose.Words.MailMerging
    
    Namespace MailMergeFormFields
        ''' <summary>
        ''' This sample shows how to insert check boxes and text input form fields during mail merge into a document.
        ''' </summary>
        Friend Class Program
            ''' <summary>
            ''' The main entry point for the application.
            ''' </summary>
            Public Shared Sub Main(ByVal args() As String)
                Dim program As New Program()
                program.Execute()
            End Sub
    
            Private Sub Execute()
                Dim exeDir As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar
                Dim dataDir As String = New Uri(New Uri(exeDir), "../../Data/").LocalPath
    
                ' Load the template document.
                Dim doc As New Document(dataDir & "Template.doc")
    
                ' Setup mail merge event handler to do the custom work.
                doc.MailMerge.FieldMergingCallback = New HandleMergeField()
    
                ' This is the data for mail merge.
                Dim fieldNames() As String = {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber", "Subject", "Body", "Urgent", "ForReview", "PleaseComment"}
                Dim fieldValues() As Object = {"Josh", "Jenny", "123456789", "", "Hello", "<b>HTML Body Test message 1</b>", True, False, True}
    
                ' Execute the mail merge.
                doc.MailMerge.Execute(fieldNames, fieldValues)
    
                ' Save the finished document.
                doc.Save(dataDir & "Template Out.doc")
            End Sub
    
            Private Class HandleMergeField
                Implements IFieldMergingCallback
                ''' <summary>
                ''' This handler is called for every mail merge field found in the document,
                '''  for every record found in the data source.
                ''' </summary>
                Private Sub IFieldMergingCallback_FieldMerging(ByVal e As FieldMergingArgs) Implements IFieldMergingCallback.FieldMerging
                    If mBuilder Is Nothing Then
                        mBuilder = New DocumentBuilder(e.Document)
                    End If
    
                    ' We decided that we want all boolean values to be output as check box form fields.
                    If TypeOf e.FieldValue Is Boolean Then
                        ' Move the "cursor" to the current merge field.
                        mBuilder.MoveToMergeField(e.FieldName)
    
                        ' It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
                        Dim checkBoxName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
    
                        ' Insert a check box.
                        mBuilder.InsertCheckBox(checkBoxName, CBool(e.FieldValue), 0)
    
                        ' Nothing else to do for this field.
                        Return
                    End If
    
                    ' We want to insert html during mail merge.
                    If e.FieldName = "Body" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        mBuilder.InsertHtml(DirectCast(e.FieldValue, String))
                    End If
    
                    ' Another example, we want the Subject field to come out as text input form field.
                    If e.FieldName = "Subject" Then
                        mBuilder.MoveToMergeField(e.FieldName)
                        Dim textInputName As String = String.Format("{0}{1}", e.FieldName, e.RecordIndex)
                        mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", CStr(e.FieldValue), 0)
                    End If
                End Sub
    
                Private Sub ImageFieldMerging(ByVal args As ImageFieldMergingArgs) Implements IFieldMergingCallback.ImageFieldMerging
                    ' Do nothing.
                End Sub
    
                Private mBuilder As DocumentBuilder
            End Class
        End Class
    End Namespace
    
    

    public by fabio.nosenzo  3312  14  6  1

    Excel VBA Merge cells with same value

    Merge cells in different columns with the same value in an ordered list
    Sub merge_cells()
    Application.DisplayAlerts = False
        
        'row to be avaluated
        iRow = 1
        'number of columns to be evaluated
        iNumberOfColumns = 12
        'first Column to be evaluated
        iFirstColumn = 4
        For i = iFirstColumn + 1 To iNumberOfColumns + iFirstColumn + 1
            If Cells(iRow, i) <> Cells(iRow, i - 1) Then
            iLastRow = i - 1
            'get first column letter
            vArr = Split(Cells(1, iFirstColumn).Address(True, False), "$")
            sFirstColumn = vArr(0)
            'get last column letter
            vArr = Split(Cells(1, i - 1).Address(True, False), "$")
            sLastColumn = vArr(0)
            sRange = sFirstColumn & iRow & ":" & sLastColumn & iRow
            Range(sRange).Select
                With Selection
                    .HorizontalAlignment = xlCenter
                    .VerticalAlignment = xlCenter
                    .WrapText = True
                    .Orientation = 0
                    .AddIndent = False
                    .IndentLevel = 0
                    .ShrinkToFit = False
                    .ReadingOrder = xlContext
                    .MergeCells = False
                End With
            Selection.Merge
            iFirstColumn = i
            End If
        Next i
          
    Application.DisplayAlerts = True
    End Sub
    

    public by cghersi  9858  3  9  1

    C#: How to Convert a generic Url to absolute Uri

    This method provides an Uri object from the given URL, splitted as baseURl and extracted url, e.g. baseURL='http://www.snip2code.com', extractedUrl='./Snippet/25652'
    /// <summary>
    /// Converts a generic Url to absolute Uri
    /// </summary>
    /// <param name="baseUrl">The main url of the website</param>
    /// <param name="extractedUrl">The url to be converted</param>
    /// <returns>An absolute Uri | null</returns>
    /// -----------------------------------------------------------------------------------------------------
    static public Uri UriAbsoluteFromUrl(string baseUrl, string extractedUrl)
    {
        // The URI is in a HTTP page and could have encoded HTML char ...
        string link = HttpUtility.HtmlDecode(extractedUrl.Replace("\n", ""));
        Uri baseUri = new Uri(baseUrl);
        string siteRoot = string.Empty;
    
        // create absolute link
        if (link.StartsWith("/"))
        {
            //absolute replace
            int firstSlashPos = baseUrl.IndexOf("://");
            string protocol = baseUrl.Substring(0, firstSlashPos + 3);
            Uri siteRef = new Uri(baseUrl.Trim());
            link = string.Concat(protocol, siteRef.Host, link.Trim());
        }
        else if (link.StartsWith("./"))
        {
            //relative replace - same level
            siteRoot = baseUrl.Trim();
            siteRoot = siteRoot.TrimEnd('/');
            link = string.Format("{0}/{1}", siteRoot, link.TrimStart('.', '/'));
        }
        else if (link.StartsWith("../"))
        {
            //relative replace - multi level                                
            siteRoot = baseUrl.Trim();
            string clean = link;
    
            while (clean.StartsWith("../"))
            {
                clean = clean.Remove(0, 3);
                siteRoot = siteRoot.TrimEnd('/');
                siteRoot = siteRoot.Substring(0, siteRoot.LastIndexOf('/'));
            }
    
            link = string.Format("{0}/{1}", siteRoot, clean.TrimStart('/'));
        }
        else if (!link.Contains("://"))
        {
            //relative replace - same level
            baseUrl += "/";
            int lastSlash = baseUrl.LastIndexOf('/');
            if (lastSlash > 0 && lastSlash < baseUrl.Length)
                siteRoot = baseUrl.Substring(0, lastSlash);
            siteRoot = siteRoot.TrimEnd('/');
            link = string.Format("{0}/{1}", siteRoot, link.TrimStart('.', '/'));
        }
    
        // escape the link
        if (!Uri.IsWellFormedUriString(link, UriKind.Absolute))
            link = Uri.EscapeUriString(link);
    
        if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
            return new Uri(link);
        else
            return null;
    }
    

    public by cghersi @ Snip2CodeDev  2677  5  7  1

    C#: Prepare a string of comma-separated values from a collection.

    This method prepares a comma-separated (or any other character specified as 'separator' input) from the given list. It can also remove zero or negative inputs if explicitly required by setting removeZerosOrNegatives=true
    public static string MergeIntoCommaSeparatedString<T>(ICollection<T> idList, bool removeZerosOrNegatives, char separator = ',')
           where T : struct
    {
        string list_ids = string.Empty;
        if (idList != null)
        {
            foreach (T id in idList)
            {
                if (removeZerosOrNegatives && (Convert.ToInt64(id) <= 0))
                    continue;
                list_ids += string.Format("{0}{1}", separator, id);
            }
            list_ids = list_ids.TrimStart(separator);
        }
        return list_ids;
    }
       

    public by cghersi  2027  4  6  2

    Merge the content of two dictionaries

    Checks if the two input dictionaries has the same key: in positive case, the values corresponding to the matching keys are summed in the resulting dictionary.
    public static void MergeDictionary(ref Dictionary<string, int> container, Dictionary<string, int> input)
    {
      if (input == null)
        return;
      foreach (string key in input.Keys)
      {
        if (container.ContainsKey(key))
          container[key] += input[key];
        else
          container.Add(key, input[key]);
      }
    }
    

    public by johansonkatherine  3929  0  7  4

    Merge multiple PDFs using PHP SDK from Aspose

    PHP developers can learn how to merge multiple PDF files into a single PDF file using PHP SDK from Aspose. You can use the following given supported third party storage to access Aspose for Cloud service. https://github.com/asposeforcloud/Aspose_Cloud_SDK_For_PHP In order to use PHP SDK, you need to perform following steps: - Set base
    use Aspose\Cloud\Common\AsposeApp;
    use Aspose\Cloud\Common\Utils;
    use Aspose\Cloud\Common\Product;
    use Aspose\Cloud\Storage\Folder;
    use Aspose\Cloud\Pdf\Document;
    
    /**** Section 1 ****/
    
    AsposeApp::$appSID = "77****-****-****-****-80*********";
    AsposeApp::$appKey = "******************";
    $baseProductUri= "http://api.aspose.com/v1.1";
    AsposeApp::$outPutLocation = getcwd() . "/Output/";
    
    /**** End Section 1 ****/
    
    /**** Section 2 ****/
    
    $inputFile1 = getcwd() . "/Input/input1.pdf";
    $inputFile2 = getcwd() . "/Input/input2.pdf";
    $inputFile3 = getcwd() . "/Input/input3.pdf";
    $mergedFileName = "MergedFile.pdf";
    //upload input PDF files
    echo "Uploading main document...<br />";
    $folder = new Folder();
    $folder->UploadFile($inputFile1, "");
    $folder->UploadFile($inputFile2, "");
    $folder->UploadFile($inputFile3, "");
    echo "input files uploaded <br />";
    
    /**** End Section 2 ****/
    
    /**** Section 3 ****/
    echo "Merging PDF files... <br />";
    //create Document object
    $doc = new Document($mergedFileName);
    $result = $doc->mergeDocuments(array('input1.pdf','input2.pdf','input3.pdf'));
    
    /**** End Section 3 ****/
    
    

    public by johansonkatherine  4029  1  7  3

    Merge multiple PDFs using PHP REST API

    PHP developers can learn how to merge multiple PDF files into a single PDF file using PHP REST API and SDK. To merge PDFs, you need to upload input PDFs to Aspose for Cloud Service or any supported third party storage and then send a PUT request to Aspose for Cloud service. This REST example uses PHP CURL library to send HTTP request and handle
    /**** Section 1 ****/        
    
    $appSID = '77****-****-****-****-80*********';
    $appKey = '****************';
    //build URI to merge PDFs
    $strURI = 'http://api.aspose.com/v1.1/pdf/MergedFile.pdf/merge';
    //sign URI
    $signedURI = sign($strURI, $appSID, $appKey);
    
    /**** End Section 1 ****/
    
    /**** Section 2 ****/
    
    //Build JSON to post
    $documentsList = array('List'=> array('input1.pdf', 'input2.pdf', 'input3.pdf'));
    $json = json_encode($documentsList);
    
    /**** End Section 2 ****/
    
    /**** Section 3 ****/
    $responseStream = processCommand($signedURI, 'PUT', 'json', $json);
    
    /**** End Section 3 ****/
    
    /**** Section 4 ****/
    
    //Download merged PDF
    //build URI
    $strURI = 'http://stage.aspose.com/v1.1/storage/file/MergedFile.pdf';
    //sign URI
    $signedURI = sign($strURI, $appSID, $appKey);
    $responseStream = processCommand($signedURI, "GET", "", "");
    $outputPath = getcwd() . '/output/MergedFile.pdf';
    saveFile($responseStream, $outputPath);
    echo 'Files have been merged and output file has been saved at: ' . $outputPath;
    
    /**** End Section 4 ****/ 
    

    public by johansonkatherine  4051  0  6  3

    Merge Multiple Word Documents into Single Doc using REST API in Python

    This REST example uses pycurl library to send HTTP request and handle HTTP response so you need to install it to use this example. Once input Word documents are uploaded, you can use the following URI to merge documents on Aspose for Cloud or any supported third party storage. http://api.aspose.com/v1.1/words/MainDocument.docx/appendDocument
          ####### Section 1 ######
          # specify App SID
    AsposeApp.app_sid = '77****-****-****-****-80*********'
          # specify App Key
    AsposeApp.app_key = '******************'
          #build URI to merge PDFs
    str_uri = 'http://api.aspose.com/v1.1/words/MainDocument.docx/appendDocument'
          #sign URI
    signed_uri = Utils.sign(Utils(), str_uri)
    
          ####### End Section 1 ######
    
          ####### Section 2 ######
          #Build JSON to post
          json_document1 = json.dumps({'Href' : 'AppendDocument1.docx', 'ImportFormatMode' : 'KeepSourceFormatting'})
          json_document2 = json.dumps({'Href' : 'AppendDocument2.docx', 'ImportFormatMode' : 'UseDestinationStyles'})
    json_arr = '{\'DocumentEntries\':[' + json_document1 + ',' + json_document2 + ']}'
    
       ####### End Section 2 ######
    
         ####### Section 3 ######
    Utils.process_command(Utils(), signed_uri, 'POST', 'JSON', json_arr)
          ####### End Section 3 ######
    
          ####### Section 4 ######
    
          #build URI to download output file
    str_uri = 'http://api.aspose.com/v1.1/storage/file/MainDocument.docx'
          #sign URI
    signed_uri = Utils.sign(Utils(), str_uri)
    response_stream = Utils.process_command(Utils(),signed_uri, 'GET')
    Utils.save_file(Utils(),response_stream, 'MergedFile.docx')
    
          ####### End Section 4 ###### 
    

    public by MatteoP  2635  1  6  1

    Batch merge txt files

    Short batch script to merge the txt file in a folder. The output file initially has a different extension to avoid the instance in which the for loop would find it and add it to itself. (another possible solution to this is making sure the output file is the first alphabetically and does not exist yet, so it is created after the loop has began rea
    @echo off
    for %f in (*.txt) do(
    type "%f" >> output.txx
    echo. >> output.txx
    )
    ren output.txx output.txt   

    public by rioxshen  1776  0  5  1

    [leetcode] Merge Intervals

    #!/usr/bin/env python
    
    class Interval:
      def __init__(self, s=0, e=0):
        self.start = s
        self.end = e
    
    
    class Solution:
      def merge(self, intervals):
        """ Merges intercestions.
        
        To avoid overlapping problem, first sorts the list by start.
        Iterate through the sorted list and merge intercestions.
        """
        if not intervals or len(intervals) <= 1:
          return intervals
        
        # Sort the list
        intervals.sort(lambda x,y: x.start-y.start)
        
        result = []
        length = len(intervals)
        last = intervals[0]
        for i in range(1, length):
          current = intervals[i]
          if current.start <= last.end: # Merges intercetion
            last.end = max(last.end, current.start)
          else:
            result.append(last)
            last = current
        
        # Appends the last element in intervals list
        result.append(last)
        return result
    • Public Snippets
    • Channels Snippets