I want to insert a merge field to an existing word doc. Am able to create a xml element of merge field but am not sure on how to append that to the document. Below is my code
Microsoft.Office.Interop.Word.Document wrdDoc = Globals.ThisAddIn.Application.ActiveDocument;
From above I will get the active document
string instructionText = String.Format(" MERGEFIELD {0} \\* MERGEFORMAT", cmbType.Text + "__" + cmbField.Text);
SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };
DocumentFormat.OpenXml.Wordprocessing.Run run1 = new DocumentFormat.OpenXml.Wordprocessing.Run();
RunProperties runProperties1 = new RunProperties();
NoProof noProof1 = new NoProof();
runProperties1.Append(noProof1);
Text text1 = new Text();
text1.Text = String.Format("«{0}»", cmbType.Text + "__" + cmbField.Text);
run1.Append(runProperties1);
run1.Append(text1);
simpleField1.Append(run1);
DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
paragraph.Append(new OpenXmlElement[] { simpleField1 });
Here am creating a paragraph. Now how can i append this paragraph element to the wrdDoc
Word.MailMerge wrdMailMerge;
Word.Selection wrdSelection;
Word.MailMergeFields wrdMergeFields;
Microsoft.Office.Interop.Word.Document wrdDoc = Globals.ThisAddIn.Application.ActiveDocument;
Microsoft.Office.Interop.Word.Application wrdApp = Globals.ThisAddIn.Application;
wrdSelection = wrdApp.Selection;
wrdMailMerge = wrdDoc.MailMerge;
wrdMergeFields = wrdMailMerge.Fields;
wrdSelection.ParagraphFormat.Alignment =
Word.WdParagraphAlignment.wdAlignParagraphJustify;
wrdMergeFields.Add(wrdSelection.Range, fieldname);
Related
I'm using iTextSharp to create an invoice in PDF.
Now I need to create multiple copies of that PDF, adding headers such as "DUPLICATE", "TRIPLICATE", and so on.
Is that possible?
Document pdfDoc = new Document(PageSize.A4, 20, 25, 25, 10);
System.IO.FileStream file = new System.IO.FileStream(Server.MapPath("~/" + fileUploadLoc + "/" + "File.pdf", System.IO.FileMode.OpenOrCreate);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, file);
fileName = Convert.ToString("Invoice.pdf");
pdfDoc.Open();
pdfWriter.Open();
PdfPTable nested = new PdfPTable(1);
nested.DefaultCell.Border = Rectangle.BOX;
nested.WidthPercentage = 100;
PdfPCell Tableheader = new PdfPCell(new Phrase("Company Name", titleHeaderFont));
Tableheader.HorizontalAlignment = 1;
Tableheader.Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER;
Tableheader.Left = 45f;
Tableheader.Right = 45f;
table.AddCell(Tableheader);
PdfPCell Tableheader7 = new PdfPCell(new Phrase("Triplicate for Supplier", fontsize7normaol));
////Above line has to be changed in each new pdf
Tableheader7.HorizontalAlignment = 1;
Tableheader7.Border = Rectangle.LEFT_BORDER |
Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER |
Rectangle.TOP_BORDER;
Tableheader7.Right = 25f;
nested1.AddCell(Tableheader7);
pdfDoc.Add(table);
pdfWriter.CloseStream = false;
pdfDoc.Close();
I am programmatically creating InfoPath forms in a form library within SharePoint 2010 from data in a CSV file. It all works fine apart from the date fields. The form will refuse to open with a format error. I have tried multiple ways of formatting the date but no luck so far. Code below...
If I format 2016-10-10 then it does show in the Forms Library view but I still can not open the form. It just shows a datatype error.
// Get the data from CSV file.
string[,] values = LoadCsv("ImportTest.csv");
//Calulate how many columns and rows in the dataset
int countCols = values.GetUpperBound(1) + 1;
int countRows = values.GetUpperBound(0) + 1;
string rFormSite = "siteurl";
// opens the site
SPWeb webSite = new SPSite(rFormSite).OpenWeb();
// gets the blank file to copy
SPFile BLANK = webSite.Folders["EventSubmissions"].Files["Blank.xml"];
// reads the blank file into an xml document
MemoryStream inStream = new MemoryStream(BLANK.OpenBinary());
XmlTextReader reader = new XmlTextReader(inStream);
XmlDocument xdBlank = new XmlDocument();
xdBlank.Load(reader);
reader.Close();
inStream.Close();
//Get latest ID from the list
int itemID = GetNextID(webSite, "EventSubmissions");
if (itemID == -1) return;
//Iterate each row of the dataset
for (int row = 1; row < countRows; row++)
{
//display current event name
Console.WriteLine("Event name - " + values[row, 4]);
XmlDocument xd = xdBlank;
XmlElement root = xd.DocumentElement;
//Cycling through all columns of the document//
for (int col = 0; col < countCols; col++)
{
string field = values[0, col];
string value = values[row, col];
switch (field)
{
case "startDate":
value = //How do format the date here ;
break;
case "endDate":
value = "";
break;
case "AutoFormID":
value = itemID.ToString();
break;
}
XmlNodeList nodes = xd.GetElementsByTagName("my:" + field);
foreach (XmlNode node in nodes)
{
node.InnerText = value;
}
}
// saves the XML Document back as a file
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
SPFile newFile = webSite.Folders["EventSubmissions"].Files.Add(itemID.ToString() + ".xml", (encoding.GetBytes(xd.OuterXml)), true);
itemID++;
}
Console.WriteLine("Complete");
Console.ReadLine();
Thanks
For me this worked
DateTime.Now.ToString("yyyy-MM-dd")
I have 60 PDF files I would like to show (Print) in single PDF. I have already tried googling it but it was no use for me, as all PDF append in to a single page. How do I resolve this (I'm an new to this)
Here is my code:
var jasperPrint1 = JasperFillManager.fillReport(jasperReport1, params1, new JREmptyDataSource());
var pages = jasperPrint1.getPages();
for( j <- 0 to pages.size()-1){
var obj = pages.get(j)
jasperPrint.addPage(obj)
}
var outDir: String = java.lang.System.getProperty("user.dir");
separator = java.io.File.separator;
outDir = outDir + separator + "public" + separator + "sample.pdf"
var baos = new java.io.ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
var outputStream = new java.io.FileOutputStream(outDir);
baos.writeTo(outputStream);
i am a new member an i really like this site because it help me always
my problem is
i want replace word document using openxml and add a page break
end then i want to write replaced text second page
here my codes
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(#"d:\a.docx", true))
{
using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
text = reader.ReadToEnd();
}
Regex regexText = new Regex("#db#");
text = regexText.Replace(text, textBox4.Text.Trim());
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(text);
}
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
Run r = new Run();
Paragraph para = new Paragraph(new Run(new Break() { Type = BreakValues.Page }));
using (StreamWriter sw1 = new StreamWriter(mainPart.GetStream(FileMode.Create)))
{
sw1.Write(text);
}
mainPart.Document.Body.InsertAfter(para, mainPart.Document.Body.LastChild);
mainPart.Document.Save();
}
}
I suggest you insert a page break in your a.docx in advance. Then, use MergeField to locate where you want to replace with.
Here is the example
Hope that someone can help me as soon as possible :-)
I would like to know how can we search Multiple Sites using Lucene??! (All sites are in one index).
I have succeeded to search one website, and to index multiple sites, however I am not able to search all websites.
Consider this method that I have:
private void PerformSearch()
{
DateTime start = DateTime.Now;
//Create the Searcher object
string strIndexDir = Server.MapPath("index") + #"\" + mstrURL;
IndexSearcher objSearcher = new IndexSearcher(strIndexDir);
//Parse the query, "text" is the default field to search
Query objQuery = QueryParser.Parse(mstrQuery, "text", new StandardAnalyzer());
//Create the result DataTable
mobjDTResults.Columns.Add("title", typeof(string));
mobjDTResults.Columns.Add("path", typeof(string));
mobjDTResults.Columns.Add("score", typeof(string));
mobjDTResults.Columns.Add("sample", typeof(string));
mobjDTResults.Columns.Add("explain", typeof(string));
//Perform search and get hit count
Hits objHits = objSearcher.Search(objQuery);
mintTotal = objHits.Length();
//Create Highlighter
QueryHighlightExtractor highlighter = new QueryHighlightExtractor(objQuery, new StandardAnalyzer(), "<B>", "</B>");
//Initialize "Start At" variable
mintStartAt = GetStartAt();
//How many items we should show?
int intResultsCt = GetSmallerOf(mintTotal, mintMaxResults + mintStartAt);
//Loop through results and display
for (int intCt = mintStartAt; intCt < intResultsCt; intCt++)
{
//Get the document from resuls index
Document doc = objHits.Doc(intCt);
//Get the document's ID and set the cache location
string strID = doc.Get("id");
string strLocation = "";
if (mstrURL.Substring(0,3) == "www")
strLocation = Server.MapPath("cache") +
#"\" + mstrURL + #"\" + strID + ".htm";
else
strLocation = doc.Get("path") + doc.Get("filename");
//Load the HTML page from cache
string strPlainText;
using (StreamReader sr = new StreamReader(strLocation, System.Text.Encoding.Default))
{
strPlainText = ParseHTML(sr.ReadToEnd());
}
//Add result to results datagrid
DataRow row = mobjDTResults.NewRow();
if (mstrURL.Substring(0,3) == "www")
row["title"] = doc.Get("title");
else
row["title"] = doc.Get("filename");
row["path"] = doc.Get("path");
row["score"] = String.Format("{0:f}", (objHits.Score(intCt) * 100)) + "%";
row["sample"] = highlighter.GetBestFragments(strPlainText, 200, 2, "...");
Explanation objExplain = objSearcher.Explain(objQuery, intCt);
row["explain"] = objExplain.ToHtml();
mobjDTResults.Rows.Add(row);
}
objSearcher.Close();
//Finalize results information
mTsDuration = DateTime.Now - start;
mintFromItem = mintStartAt + 1;
mintToItem = GetSmallerOf(mintStartAt + mintMaxResults, mintTotal);
}
As you can see that I use the site URL mstrURL when I create the search object
string strIndexDir = Server.MapPath("index") + #"\" + mstrURL;
How can I do the same when I want to search multiple sites??
Actually I am using this code.
Combine each of your site's Searcher within a MultiSearcher
See this question for more details:
Multiple Indexes search in Lucene.Net