コード例 #1
0
        private static string sqliteDbLocation = ConfigurationManager.AppSettings["sqliteDBLocation"].ToString(); //数据库存放路径


        public static void CreateTable(string bookName, DataTable dt)
        {
            try
            {
                builder.MoveToBookmark(bookName);
                //builder.StartTable();//开始画Table

                Aspose.Words.Tables.Table table = builder.StartTable();
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; // RowAlignment.Center;

                string str = string.Empty;

                builder.RowFormat.Height = 20;
                //builder.RowFormat.HeightRule = HeightRule.Auto;

                //添加列头
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    builder.InsertCell();
                    //Table单元格边框线样式
                    builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                    //Table此单元格宽度
                    builder.CellFormat.Width = 500;

                    //此单元格中内容垂直对齐方式
                    builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
                    builder.CellFormat.HorizontalMerge   = Aspose.Words.Tables.CellMerge.None;
                    builder.CellFormat.VerticalMerge     = Aspose.Words.Tables.CellMerge.None;
                    //字体大小
                    builder.Font.Size = 10;
                    //是否加粗
                    builder.Bold = true;
                    //向此单元格中添加内容
                    builder.Write(dt.Columns[i].ColumnName);
                }
                builder.EndRow();

                //添加每行数据
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    builder.RowFormat.HeightRule = HeightRule.Auto;
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        str = dt.Rows[i][j].ToString();
                        //插入Table单元格
                        builder.InsertCell();

                        //Table单元格边框线样式
                        builder.CellFormat.Borders.LineStyle = LineStyle.Single;

                        //Table此单元格宽度 跟随列头宽度
                        builder.CellFormat.Width = 500;

                        //此单元格中内容垂直对齐方式
                        builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;

                        builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
                        builder.CellFormat.VerticalMerge   = Aspose.Words.Tables.CellMerge.None;

                        //字体大小
                        builder.Font.Size = 10;
                        //是否加粗
                        builder.Bold = false;

                        //向此单元格中添加内容
                        builder.Write(str);
                    }

                    //Table行结束
                    builder.EndRow();
                }
                table.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths);///设置表格宽度   适应设置的宽度
                builder.EndTable();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
                //addLog("插入表格出现 " + ex.Message);
            }
        }
コード例 #2
0
        public override void Evaluate(NBMessageAssembly inputAssembly)
        {
            NBOutputTerminal outTerminal = OutputTerminal("Out");

            NBMessage inputMessage = inputAssembly.Message;

            // Create a new message from a copy of the inboundMessage, ensuring it is disposed of after use
            using (NBMessage outputMessage = new NBMessage(inputMessage))
            {
                isError = false;
                NBMessageAssembly outAssembly = new NBMessageAssembly(inputAssembly, outputMessage);
                NBElement         inputRoot   = inputMessage.RootElement;
                NBElement         outputRoot  = outputMessage.RootElement;

                #region UserCode
                try
                {
                    // check if we need to just do a test
                    if (inputRoot["JSON"]["Data"]["headTest"] == null)
                    {
                        requestId = inputRoot["JSON"]["Data"]["requestId"].ValueAsString;

                        if (inputRoot["JSON"]["Data"]["asyncRequest"] != null)
                        {
                            String uploadFileName = "";

                            if (inputRoot["JSON"]["Data"]["templateDetails"]["templates"].FirstChild["isZipUpload"].ValueAsString == "FALSE")
                            {
                                uploadFileName = inputRoot["JSON"]["Data"]["templateDetails"]["templates"].FirstChild["generatedName"].ValueAsString;
                                uploadFileName = ReplaceDateTimeReferences(uploadFileName);
                            }

                            getUploadFileLocation(outputRoot, uploadFileName, inputRoot, requestId);
                        }
                        else
                        {
                            outputRoot["JSON"]["Data"].DeleteAllChildren();
                            applyLicense(outputRoot);

                            if (isError == false)
                            {
                                var pdfStreams       = new List <PDFStream>();
                                var nonZipPDFStreams = new List <PDFStream>();

                                foreach (NBElement template in inputRoot["JSON"]["Data"]["templateDetails"]["templates"])
                                {
                                    String patentDataItem  = template["parentDataItem"].ValueAsString;
                                    String csvCollatedFile = "";
                                    String isZipUpload     = template["isZipUpload"].ValueAsString;

                                    String inputFileExtension  = Path.GetExtension(template["templateName"].ValueAsString.ToUpper());
                                    String outputFileExtension = Path.GetExtension(template["generatedName"].ValueAsString.ToUpper());

                                    InputFileTypes  inputFileType  = (InputFileTypes)Enum.Parse(typeof(InputFileTypes), inputFileExtension.Replace(".", ""), true);
                                    OutputFileTypes outputFileType = (OutputFileTypes)Enum.Parse(typeof(OutputFileTypes), outputFileExtension.Replace(".", ""), true);

                                    String templateContent = "";

                                    if (inputFileType != InputFileTypes.CSV)
                                    {
                                        templateContent = System.IO.File.ReadAllText(template["templateLocation"].ValueAsString);
                                    }

                                    NBElement envIn = inputRoot["JSON"]["Data"];

                                    String documentIdentifierField = "";

                                    if (envIn["documentIdentifierField"] != null)
                                    {
                                        documentIdentifierField = envIn["documentIdentifierField"].ValueAsString;
                                    }

                                    Boolean elementFound = true;

                                    foreach (String elementName in patentDataItem.Split('.'))
                                    {
                                        if (envIn[elementName] != null)
                                        {
                                            envIn = envIn[elementName];
                                        }
                                        else
                                        {
                                            elementFound = false;
                                            break;
                                        }
                                    }

                                    if (elementFound == true && envIn.Children().Count() > 0)
                                    {
                                        List <NBElement> elementsToProcess = new List <NBElement>();

                                        if (envIn.FirstChild.Name == "Item" && envIn.LastChild.Name == "Item")
                                        {
                                            elementsToProcess = envIn.ToList();
                                        }
                                        else
                                        {
                                            elementsToProcess.Add(envIn);
                                        }

                                        String outputFileName = template["generatedName"].ValueAsString;


                                        if (outputFileType != OutputFileTypes.CSV)
                                        {
                                            Parallel.ForEach(elementsToProcess, docData =>
                                            {
                                                String documentContent = templateContent;
                                                String templateName    = outputFileName;

                                                String identifier = "";

                                                if (documentIdentifierField != "")
                                                {
                                                    identifier  = ReplaceAllFields(docData, "[[" + documentIdentifierField + "]]");
                                                    isZipUpload = "FALSE";
                                                }

                                                documentContent = ReplaceAllFields(docData, documentContent);
                                                templateName    = ReplaceAllFields(docData, templateName);


                                                //Example of IF field - [[IFdepositAccount!=""|Deposit Account|]]
                                                Regex ifregex = new Regex(string.Format("\\[IF.*?\\]]"));
                                                foreach (Match m in ifregex.Matches(documentContent))
                                                {
                                                    String fieldContent = getFieldContent(docData, m.Value.Replace("[", "").Replace("]", ""));
                                                    documentContent     = documentContent.Replace("[" + m.Value, fieldContent);
                                                }

                                                //Example of IF field - [[FORMATrenewalDate|dd-MM-yyyy]]
                                                Regex formatregex = new Regex(string.Format("\\[FORMAT.*?\\]]"));
                                                foreach (Match m in formatregex.Matches(documentContent))
                                                {
                                                    String fieldName = m.Value.Replace("[", "").Replace("]", "");
                                                    if (fieldName.IndexOf('|') > -1)
                                                    {
                                                        String fieldFormat = fieldName.Split('|')[1];
                                                        fieldName          = fieldName.Split('|')[0].Replace("FORMAT", "");

                                                        String fieldContent = ReplaceAllFields(docData, "[[" + fieldName + "]]");

                                                        if (fieldContent != "")
                                                        {
                                                            switch (fieldFormat.ToLower())
                                                            {
                                                            case "caps":
                                                                fieldContent = fieldContent.First().ToString().ToUpper() + fieldContent.Substring(1);
                                                                break;

                                                            case "camelcase":
                                                                fieldContent = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fieldContent);
                                                                break;

                                                            case "lower":
                                                                fieldContent = fieldContent.ToLower();
                                                                break;

                                                            case "upper":
                                                                fieldContent = fieldContent.ToUpper();
                                                                break;

                                                            default:
                                                                try
                                                                {
                                                                    DateTime parsedDate;
                                                                    String pattern = "yyyy-MM-dd";
                                                                    if (DateTime.TryParseExact(fieldContent, pattern, null, System.Globalization.DateTimeStyles.None, out parsedDate))
                                                                    {
                                                                        fieldContent = String.Format("{0:" + fieldFormat + "}", parsedDate);
                                                                    }
                                                                    else
                                                                    {
                                                                        fieldContent = String.Format("{0:" + fieldFormat + "}", fieldContent);
                                                                    }
                                                                }
                                                                catch { }
                                                                break;
                                                            }
                                                        }
                                                        documentContent = documentContent.Replace("[" + m.Value, fieldContent);
                                                    }
                                                }

                                                List <string> tables = new List <string>();

                                                String docTable = documentContent;
                                                while (docTable.IndexOf("[[##TABLE") > 0)
                                                {
                                                    int start = docTable.IndexOf("[[##TABLE");
                                                    int end   = docTable.IndexOf("TABLE##]]");

                                                    if (end <= 0)
                                                    {
                                                        break;
                                                    }

                                                    tables.Add(docTable.Substring(start + 9, end - start - 10));
                                                    docTable = docTable.Substring(end + 1);
                                                }

                                                var rtfBuilder           = new RTFBuilder();
                                                List <String> tableNames = new List <string>();

                                                // replace any table definitions
                                                foreach (String table in tables)
                                                {
                                                    // Get Column Definitions
                                                    String groupDataItem = "";
                                                    String tableName     = "";
                                                    List <CommonDefinitions.ColumnDefinition> colDefs = new List <CommonDefinitions.ColumnDefinition>();
                                                    List <CommonDefinitions.TotalColumns> totalCols   = new List <CommonDefinitions.TotalColumns>();

                                                    foreach (String sColDef in table.Split('|'))
                                                    {
                                                        if (sColDef == table.Split('|')[0])
                                                        {
                                                            tableName     = sColDef.Split(':')[0];
                                                            groupDataItem = sColDef.Split(':')[1];
                                                        }
                                                        else
                                                        {
                                                            if (sColDef.Split(':').Count() == 2)
                                                            {
                                                                colDefs.Add(new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1]));
                                                            }
                                                            if (sColDef.Split(':').Count() == 3)
                                                            {
                                                                CommonDefinitions.ColumnDefinition colDef = new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1], sColDef.Split(':')[2]);
                                                                colDefs.Add(colDef);
                                                                if (colDef.isTotalColumn == true)
                                                                {
                                                                    totalCols.Add(new CommonDefinitions.TotalColumns(tableName, (totalCols.Count + 1), colDef.fieldName));
                                                                }
                                                            }
                                                            if (sColDef.Split(':').Count() == 4)
                                                            {
                                                                CommonDefinitions.ColumnDefinition colDef = new CommonDefinitions.ColumnDefinition(sColDef.Split(':')[0], sColDef.Split(':')[1], sColDef.Split(':')[2], sColDef.Split(':')[3]);
                                                                colDefs.Add(colDef);
                                                                if (colDef.isTotalColumn == true)
                                                                {
                                                                    totalCols.Add(new CommonDefinitions.TotalColumns(tableName, (totalCols.Count + 1), colDef.fieldName));
                                                                }
                                                            }
                                                        }
                                                    }

                                                    tableNames.Add(tableName);

                                                    byte[] tableByteArray    = Encoding.ASCII.GetBytes(documentContent);
                                                    MemoryStream tableStream = new MemoryStream(tableByteArray);
                                                    //Document tableDoc = new Document(tableStream);

                                                    Document tableDoc       = new Document();
                                                    DocumentBuilder builder = new DocumentBuilder(tableDoc);

                                                    builder.Write("##" + tableName + "START##");
                                                    builder.Writeln();

                                                    Aspose.Words.Tables.Table tbl = builder.StartTable();

                                                    builder.CellFormat.Borders.Top.LineStyle    = LineStyle.None;
                                                    builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Single;
                                                    builder.CellFormat.Borders.Right.LineStyle  = LineStyle.None;
                                                    builder.CellFormat.Borders.Left.LineStyle   = LineStyle.None;

                                                    builder.CellFormat.TopPadding    = 4;
                                                    builder.CellFormat.BottomPadding = 4;
                                                    builder.CellFormat.LeftPadding   = 0;

                                                    ParagraphFormat paragraphFormat = builder.ParagraphFormat;
                                                    paragraphFormat.Alignment       = ParagraphAlignment.Left;
                                                    paragraphFormat.LeftIndent      = 0;

                                                    builder.Font.Name = "Arial";
                                                    builder.Font.Size = 10;
                                                    builder.Font.Bold = true;

                                                    builder.Font.Bold  = false;
                                                    Color headerFont   = new Color();
                                                    headerFont         = Color.FromArgb(39, 55, 96);
                                                    builder.Font.Color = headerFont;

                                                    foreach (CommonDefinitions.ColumnDefinition colDef in colDefs)
                                                    {
                                                        builder.InsertCell();
                                                        if (colDef == colDefs.First())
                                                        {
                                                            builder.StartBookmark(tableName + "START");
                                                            builder.EndBookmark(tableName + "START");
                                                        }
                                                        tbl.LeftIndent = -42;

                                                        tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths);
                                                        builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth);

                                                        builder.Write(colDef.columnName);
                                                    }

                                                    builder.EndRow();

                                                    NBElement rowItems = docData;
                                                    foreach (String elementName in groupDataItem.Split('.'))
                                                    {
                                                        rowItems = rowItems[elementName];
                                                    }

                                                    builder.Font.Bold  = false;
                                                    Color contentFont  = new Color();
                                                    contentFont        = Color.FromArgb(128, 128, 128);
                                                    builder.Font.Color = contentFont;

                                                    int rowId = 1;
                                                    //foreach (NBElement row in rowItems)
                                                    //{
                                                    foreach (ColumnDefinition colDef in colDefs)
                                                    {
                                                        builder.InsertCell();
                                                        tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths);
                                                        builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth);

                                                        builder.Write("[[" + colDef.fieldName + "]]");
                                                    }
                                                    rowId++;
                                                    builder.EndRow();

                                                    foreach (ColumnDefinition colDef in colDefs)
                                                    {
                                                        builder.InsertCell();
                                                        tbl.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths);
                                                        builder.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(colDef.columnWidth);

                                                        builder.Write("[[" + colDef.fieldName + "Last]]");
                                                    }

                                                    rowId++;
                                                    builder.EndRow();

                                                    builder.EndTable();

                                                    builder.Writeln();
                                                    builder.Write("##" + tableName + "END##");

                                                    MemoryStream rtfTableStream = new MemoryStream();
                                                    tableDoc.Save(rtfTableStream, SaveFormat.Rtf);

                                                    Byte[] rtfByteArray = rtfTableStream.ToArray();
                                                    String rtfDocString = Encoding.ASCII.GetString(rtfByteArray);

                                                    String tableRowString = rtfDocString.Substring(rtfDocString.IndexOf("}\\trowd\\irow1\\") + 1, rtfDocString.IndexOf("}\\trowd\\irow2\\") - rtfDocString.IndexOf("}\\trowd\\irow1\\"));

                                                    int insertIndex = rtfDocString.IndexOf(tableRowString) + tableRowString.Length;
                                                    //String tableContents = "";
                                                    StringBuilder tableContents = new StringBuilder(rtfDocString.Substring(0, insertIndex));

                                                    int rowCount = 2;
                                                    foreach (NBElement row in rowItems)
                                                    {
                                                        String rowString = tableRowString;
                                                        foreach (ColumnDefinition colDef in colDefs)
                                                        {
                                                            String sData = "";
                                                            if (colDef.fieldName != "lineNo")
                                                            {
                                                                if (row[colDef.fieldName] != null)
                                                                {
                                                                    sData = row[colDef.fieldName].ValueAsString;
                                                                    if (sData.ToUpper() == "NULL")
                                                                    {
                                                                        sData = "";
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    sData = colDef.defaultValue;
                                                                }
                                                            }
                                                            else
                                                            {
                                                                sData = (rowCount - 1).ToString();
                                                            }

                                                            if (rowCount < rowItems.Count() + 1)
                                                            {
                                                                rowString = rowString.Replace("[[" + colDef.fieldName + "]]", sData);
                                                            }
                                                            else
                                                            {
                                                                rtfDocString = rtfDocString.Replace("[[" + colDef.fieldName + "Last]]", sData);
                                                            }
                                                        }

                                                        if (rowCount < rowItems.Count() + 1)
                                                        {
                                                            rowString = rowString.Replace("irow1", "irow" + rowCount.ToString());
                                                            tableContents.Append(rowString);
                                                        }
                                                        rowCount++;
                                                    }

                                                    tableContents.Replace(tableRowString, "");
                                                    tableContents.Append(rtfDocString.Substring(insertIndex));

                                                    String tableOnly = tableContents.ToString();

                                                    //tableOnly = tableOnly.Substring(tableOnly.IndexOf(@"\trowd", tableOnly.Length - tableOnly.IndexOf(@"{\*\latentstyles")));
                                                    int startIndex = tableOnly.IndexOf("##" + tableName + "START##") + ("##" + tableName + "START##").Length;
                                                    int endIndex   = tableOnly.IndexOf("##" + tableName + "END##");

                                                    tableOnly = tableOnly.Substring(startIndex, endIndex - startIndex);

                                                    documentContent = documentContent.Replace("[[##TABLE" + table + "|TABLE##]]", tableOnly);
                                                }


                                                // replace any items not found in the dataset
                                                Regex regex     = new Regex(string.Format("\\[.*?\\]]"));
                                                documentContent = regex.Replace(documentContent, "");

                                                templateName = ReplaceDateTimeReferences(templateName);

                                                byte[] byteArray = Encoding.ASCII.GetBytes(documentContent);

                                                MemoryStream stream = new MemoryStream(byteArray);

                                                Document doc = new Document(stream);
                                                stream.Dispose();

                                                //String tempFileName = @"c:\temp\FileTest\" + Guid.NewGuid().ToString();
                                                //File.WriteAllText(tempFileName, documentContent);
                                                //Document doc = new Document(tempFileName);
                                                //File.Delete(tempFileName);

                                                foreach (String tableName in tableNames)
                                                {
                                                    Bookmark bm = doc.Range.Bookmarks[tableName + "START"];
                                                    Aspose.Words.Tables.Table t = (Aspose.Words.Tables.Table)bm.BookmarkStart.GetAncestor(NodeType.Table);

                                                    foreach (Aspose.Words.Tables.Cell c in t.GetChildNodes(NodeType.Cell, true))
                                                    {
                                                        foreach (Run run in c.GetChildNodes(NodeType.Run, true))
                                                        {
                                                            Aspose.Words.Font font = run.Font;
                                                            Color contentFont      = new Color();
                                                            contentFont            = Color.FromArgb(128, 128, 128);
                                                            font.Color             = contentFont;
                                                            font.Name = "Arial";
                                                        }
                                                    }
                                                    foreach (Aspose.Words.Tables.Cell c in t.FirstRow.Cells)
                                                    {
                                                        foreach (Run run in c.GetChildNodes(NodeType.Run, true))
                                                        {
                                                            Aspose.Words.Font font = run.Font;
                                                            Color contentFont      = new Color();
                                                            contentFont            = Color.FromArgb(39, 55, 96);
                                                            font.Color             = contentFont;
                                                            font.Name = "Arial";
                                                            font.Bold = true;
                                                        }
                                                    }
                                                }

                                                MemoryStream pdfStream = new MemoryStream();

                                                doc.Save(pdfStream, SaveFormat.Pdf);

                                                PDFStream pdfs = new PDFStream(pdfStream.ToArray(), templateName, identifier);
                                                pdfStream.Close();

                                                if (isZipUpload == "TRUE")
                                                {
                                                    pdfStreams.Add(pdfs);
                                                }
                                                else
                                                {
                                                    nonZipPDFStreams.Add(pdfs);
                                                }
                                                //}
                                            });
                                        }

                                        if (outputFileType == OutputFileTypes.CSV)
                                        {
                                            foreach (NBElement docData in elementsToProcess)
                                            {
                                                csvCollatedFile  = docData["headerRow"].ValueAsString;
                                                csvCollatedFile += Environment.NewLine;

                                                Boolean isFirstRow = true;

                                                foreach (NBElement row in docData["rows"])
                                                {
                                                    if (isFirstRow == true)
                                                    {
                                                        isFirstRow = false;
                                                    }
                                                    else
                                                    {
                                                        csvCollatedFile += Environment.NewLine;
                                                    }

                                                    csvCollatedFile += row.ValueAsString;
                                                }
                                            }

                                            byte[] byteArray = Encoding.ASCII.GetBytes(csvCollatedFile);
                                            outputFileName = ReplaceDateTimeReferences(outputFileName);
                                            outputFileName = getUploadFileName(outputFileName, inputRoot);

                                            if (isZipUpload == "TRUE")
                                            {
                                                pdfStreams.Add(new PDFStream(byteArray, outputFileName));
                                            }
                                            else
                                            {
                                                nonZipPDFStreams.Add(new PDFStream(byteArray, outputFileName));
                                            }
                                        }
                                    }
                                }

                                if (pdfStreams.Count() > 0)
                                {
                                    byte[] zipContent = writeContentToZip(pdfStreams, outputRoot);
                                    writeFileToBlobStore(outputRoot, zipContent, inputRoot, requestId);
                                }

                                if (nonZipPDFStreams.Count() > 0)
                                {
                                    writeMultiFilesToBlobStore(outputRoot, nonZipPDFStreams, inputRoot, requestId);
                                    outputRoot["JSON"]["Data"].CreateFirstChild("requestId").SetValue(requestId);
                                }
                            }
                        }
                    }
                    else
                    {
                        outputRoot["JSON"]["Data"].DeleteAllChildren();
                        checkBlobStore(inputRoot, outputRoot);
                    }
                }
                catch (Exception e)
                {
                    handleError("PDF10000", e, outputRoot, "General Error in PDF Generation Process");
                }

                #endregion UserCode
                // Change the following if not propagating message to the 'Out' terminal
                outTerminal.Propagate(outAssembly);
            }
        }