insert from RichTextBox into a doc file using OpenXml - c#

I want to insert what is writting in a richtextbox into a doc file footer, when i change text1.Text = "Footer" to text1.Text = txtFoot.text, an error appeared " An object reference is required for the non-static field, method, or property 'Form2.txtFoot' ", and when i tried " Text txt = txtFoot.text ", another error appeared " cannot convert string into documentformat.openxml.wordprocessing.text ", how can i fix this ?
static void GenerateFooterPartContent(FooterPart part)
{
Footer footer1 = new Footer() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
footer1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
footer1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
footer1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
footer1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
footer1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
footer1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
footer1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
footer1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
footer1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
footer1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
footer1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
footer1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
footer1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
footer1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
footer1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "00164C17", RsidRunAdditionDefault = "00164C17" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footer" };
paragraphProperties1.Append(paragraphStyleId1);
Run run1 = new Run();
Text text1 = new Text();
text1.Text = "Footer";
run1.Append(text1);
paragraph1.Append(paragraphProperties1);
paragraph1.Append(run1);
footer1.Append(paragraph1);
part.Footer = footer1;
}

text1.Text here is actually a Wordprocessing.Text, not a string object. In order to assign the text to it, you will have to do this-
text1.Text = new Text(txtFoot.text);

Related

How to center align and set bold a text in itext7

I am new to using itext for generating a pdf. I had a problem, I have added itext7 in my references
to add a pdf with values. I wanted to center align and set bold a text field in my pdf. I have looked at various examples. However,.SetBold and chunk shows error in visual studio.
This is the function which I am calling for the pdf.
[HttpGet]
[Route("GetCoilWiseReport")]
public HttpResponseMessage GetCoilWiseReport(string jwt, string fixture="", string
type="", string ID= "",
string delivery = "", string invoice = "", string wagon = "", string location = "",
string ICHP= "",string remarks="",string date="")
{
if (!Common.VerificationToken.VerifyJWToken(jwt))
{
return null;
}
var doc_date = DateTime.Now.Date.ToString("dd/MM/yyyy").Replace("-", "/");
var Type1 = type;
var id1 = ID;
var delivery1 = delivery;
var invoice1= invoice;
var wagon1 = wagon;
var location1 = location;
var ICHP1 = ICHP;
var remarks1 = remarks;
var date1 = date;
string pdfDocument = #"D:\Annexure_One IT.pdf";//Utilities.ISOP_DOCS_FOLDER +
"MasterDocs\\SupplierDespatchATP.pdf";
var dateLine = "Date:" + doc_date ;
var coilDetails = " COIL Details: " + ID;
var firstRow = "Type : " + type +" ID:"+ID+ " Delivery No:"+delivery;
var secondRow = "Invoice No.:" + invoice+" Wagon No:"+wagon+" Location:"+location;
var thirdRow = "ICHP : " + ICHP + " Remarks:" + remarks;
PdfDocument pdf = new PdfDocument(new PdfWriter(pdfDocument));
//Add new page
PageSize ps = PageSize.A4;
PdfPage page = pdf.AddNewPage(ps);
PdfCanvas canvas = new PdfCanvas(page);
iText.Layout.Document iDoc = new iText.Layout.Document(pdf, ps);
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.COURIER);
PdfFont fontBold = PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLD);
IList<String> text = new List<String>();
text.Add("");
text.Add(dateLine);
text.Add("");
text.Add("");
text.Add(coilDetails);
text.Add("");
text.Add("");
text.Add(firstRow);
text.Add("");
text.Add("");
text.Add(secondRow);
text.Add("");
text.Add("");
text.Add(thirdRow);
text.Add("");
text.Add("");
text.Add("");
text.Add("");
text.Add("");
text.Add("signature");
;
foreach (String s in text)
{
//Add text and move to the next line
//canvas.NewlineShowText(s);
if (s == "signature")
{
List<string> coilURL = new List<string>();
List<string> coilView = new List<string>();
string connectionstring = Utilities.SQL_DB1;// our SQL DB connection
SqlConnection conn1 = new SqlConnection(connectionstring);
DataTable dt = new DataTable();
string query = "Select CCD_IMAGE_URL,CCD_VIEW_DESC from T_CQL_COIL_DESC
where CCD_COIL_ID = '" + ID + "'";
//SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(query, conn1);
conn1.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; (i < dt.Rows.Count); i++)
{
coilURL.Add(imgurl + dt.Rows[i]["CCD_IMAGE_URL"].ToString());
coilView.Add(dt.Rows[i]["CCD_VIEW_DESC"].ToString());
var view = "View:"+coilView[i];
var sig = coilURL[i];
iText.Layout.Element.Paragraph p1 = new
iText.Layout.Element.Paragraph().Add(view);
//p.SetMaxHeight(20);
iDoc.Add(p1);
iText.Layout.Element.Image sigImage = new
iText.Layout.Element.Image(ImageDataFactory.Create(sig));
sigImage.SetAutoScale(true);
iText.Layout.Element.Paragraph p = new
iText.Layout.Element.Paragraph().Add(sigImage);
//p.SetMaxHeight(20);
iDoc.Add(p);
}
}
conn1.Close();
da.Dispose();
}
else
{
iText.Layout.Element.Paragraph para = new
iText.Layout.Element.Paragraph(s);
para.SetFont(font);
para.SetFontSize(9);
iDoc.Add(para);
}
}
//iDoc.Close();
//Close document
iDoc.Close();
// Add Paragraph to document
pdf.Close();
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new StreamContent(new FileStream(pdfDocument,
FileMode.Open, FileAccess.Read));
//httpResponseMessage.Content.Headers.ContentType = new
MediaTypeHeaderValue("application / vnd.openxmlformats -
officedocument.wordprocessingml.document");
httpResponseMessage.Content.Headers.ContentType = new
MediaTypeHeaderValue("application/pdf");
httpResponseMessage.Content.Headers.ContentDisposition = new
ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "Coil_Detail" +
fixture + "_" + ID + "_" + ".pdf";
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
I am trying to make CoilDetails bold and center alligned. How do I do that in the current context. Please help
Use p.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER); for aligning it in center and for setting it to bold after add try using .SetBold() or .SetFont(bold)
I do a few scripts w/ itext7 using linqpad.net in c#
but I've no issues to convert to visual studio.
here's a line in C#
p = new Paragraph(targetText).SetFontSize(12).SetTextAlignment(TextAlignment.JUSTIFIED).SetFontColor(new DeviceRgb(0, 153, 0)).SetBold();

how to create dynamic Required field Validator

I have generated an array of required field validators using following code:
Panel[] divMain = new Panel[22];
DropDownList[] gender = new DropDownList[22];
TextBox[] txtFirstName = new TextBox[22];
TextBox[] txtMiddleName = new TextBox[22];
TextBox[] txtLastName = new TextBox[22];
TextBox[] txtAge = new TextBox[22];
RequiredFieldValidator[] req = new RequiredFieldValidator[30];
and i am creating some dynamic controls using following code:
for (int i = 0; i < noOfad - 1; i++)
{
HtmlGenericControl p = new HtmlGenericControl("p");
HtmlGenericControl strong = new HtmlGenericControl("strong");
strong.InnerText = "Adult" + Convert.ToString(i + 2);
p.Controls.Add(strong);
divAdultMoreForm.Controls.Add(p);
Panel div = new Panel();
HtmlGenericControl p1 = new HtmlGenericControl("p");
p1.InnerHtml = "<span><strong>Full Name (As per Valid Govt Id Proof valid )</strong></span> <span><strong style=' margin-left: 549px;'>Age(in Years 18 +) </strong></span>";
div.Controls.Add(p1);
HtmlGenericControl p2 = new HtmlGenericControl("p");
gender[i] = new DropDownList();
gender[i].Items.Add(new ListItem("Title", "0"));
gender[i].Items.Add(new ListItem("Mr.", "1"));
gender[i].Items.Add(new ListItem("Mrs.", "2"));
gender[i].Items.Add(new ListItem("Ms.", "3"));
gender[i].CssClass = "txt";
p2.Controls.Add(gender[i]);
txtFirstName[i] = new TextBox();
txtFirstName[i].Attributes.Add("placeholder", "First Name");
txtFirstName[i].CssClass = "txt input";
txtFirstName[i].ID = "txtFirstName" + Convert.ToString(i);
req[i].ControlToValidate = txtFirstName[i].ID;//Object refrence not set to an instance ofo an object
req[i].ForeColor = System.Drawing.Color.Red;
req[i].ErrorMessage = "*";
txtFirstName[i].CssClass = "input txt";
txtMiddleName[i] = new TextBox();
txtMiddleName[i].Attributes.Add("placeholder", "Middle Name");
txtMiddleName[i].CssClass = "txt input";
txtMiddleName[i].CssClass = "input txt";
txtMiddleName[i].ID = "txtMiddleName" + Convert.ToString(i);
txtLastName[i] = new TextBox();
txtLastName[i].Attributes.Add("placeholder", "Last Name");
txtLastName[i].CssClass = "txt input";
txtLastName[i].CssClass = "input txt";
txtLastName[i].ID = "txtLastName" + Convert.ToString(i);
txtAge[i] = new TextBox();
txtAge[i].Attributes.Add("placeholder", "Enter Age");
txtAge[i].CssClass = "txt";
p2.Controls.Add(txtFirstName[i]);
p2.Controls.Add(txtMiddleName[i]);
p2.Controls.Add(txtLastName[i]);
p2.Controls.Add(txtAge[i]);
div.Controls.Add(p2);
divAdultMoreForm.Controls.Add(div);
}
But when i am assigning the control to validate to the validator req[i] then there comes an error Object reference not set to an instance of an object.
Can not understand why this problem is occuring.
Any help to correct my code!
Thanks
This is due to the fact that you forgot to initialize the RequiredFieldValidator array object. This seems to be missing from your code :
req[i] = new RequiredFieldValidator();
After this you can play with its properties.
Hope this clears it.

How to apply a different text for each image?

I have this looping intruction (foreach) which reads every image from the "GalleryImages" folder. What I want is to apply a different text for each image. Do I do this with the foreach instruction as well? Do I create a folder where I plce more .txt files?
var files = Directory.GetFiles(#".\GalleryImages");
string text22 = System.IO.File.ReadAllText(#"C:\Users\Public\TestFolder\WriteText.txt");
foreach (var file in files)
{
foreach ()
{
FileInfo fileInfo = new FileInfo(file);
WineModel wineModel = new WineModel();
wineModel.Image = new Uri(file, UriKind.Relative);
wineModel.Description = text22 + "text text text text text text text text text text text" +
Environment.NewLine + "text text text text text text text text text text text";
wineModel.Price = new Random().NextDouble();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = wineModel.Image;
bi.EndInit();
var button = new KinectTileButton
{
Label = System.IO.Path.GetFileNameWithoutExtension(file),
Background = new ImageBrush(bi),
Tag = wineModel
};
this.wrapPanel.Children.Add(button);
}
}
I've also posted the code for the click event :
private void KinectTileButtonClick(object sender, RoutedEventArgs e)
{
var button = (KinectTileButton)e.Source;
var wineModel = button.Tag as WineModel;
var selectionDisplay = new SelectionDisplay(wineModel);
this.kinectRegionGrid.Children.Add(selectionDisplay);
e.Handled = true;
}

Download multiple pdf documents using itextsharp

i have a tree view in which there are certain set of document list and another grid having patient details. what i need to do is when we select docs from treeview (select multiple..checkbox enabled) and patients from grid and click on a button should create all the documents using ITEXTSHARP.that is multiple documents are created. I tried it like this,
on button click
foreach( TreeNode node in TreeView1.Nodes)
{
if (node.ChildNodes.Count>0)
{
for(int i=0 ;i<(node.ChildNodes.Count);i++)
{
if (node.ChildNodes[i].Checked==true)
{
string nodevalue = node.ChildNodes[i].Value.ToString();
if (nodevalue=="3")
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = row.FindControl("CheckBox1") as CheckBox;
if (chk.Checked)
{
Label lbl_name = row.FindControl("Label1") as Label;
Label lbl_dob = row.FindControl("Label3") as Label;
pdf_abcd(lbl_name.Text.Trim(), lbl_dob.Text.Trim());
}
}
}
}
}
}
}
}
}
}
and the pdf_abcd function is
public void pdf_abcd(string name, string dob)
{
Phrase hospt_name = new Phrase();
Phrase slogan = new Phrase();
Phrase address = new Phrase();
Phrase pat_name = new Phrase();
Phrase phr_Consent_For_Treatment = new Phrase();
Phrase phr_Professional_Care = new Phrase();
Phrase phr_Consent_For_Treatment_head = new Phrase();
Phrase phr_Professional_Care_head = new Phrase();
Phrase phr_Nursing_Care = new Phrase();
Phrase phr_Nursing_Care_head = new Phrase();
Phrase phr_signtur_line = new Phrase();
Phrase phr_signtur_bigfont = new Phrase();
Phrase phr_signtur_smallfont_line = new Phrase();
Phrase phr_signtur_date_line = new Phrase();
Phrase phr_relationship = new Phrase();
Phrase phr_witness = new Phrase();
Phrase phr_paitient_name = new Phrase();
Phrase phr_paitient_dob = new Phrase();
Paragraph para = new Paragraph();
Paragraph pat_det = new Paragraph();
Paragraph Consent_For_Treatment = new Paragraph();
Paragraph Professional_Care = new Paragraph();
Paragraph Nursing_Care = new Paragraph();
Paragraph Consent_For_Treatment_head = new Paragraph();
Paragraph Professional_Care_head = new Paragraph();
Paragraph Nursing_Care_head = new Paragraph();
Paragraph signatur = new Paragraph();
Paragraph relationship = new Paragraph();
Paragraph witness = new Paragraph();
Paragraph paitient_name_dob = new Paragraph();
Font fntNormalText = FontFactory.GetFont(FontFactory.TIMES, 12, iTextSharp.text.Font.NORMAL);
Font fntBoldText = FontFactory.GetFont(FontFactory.TIMES, 12, Font.BOLD);
Font fntsmallText = FontFactory.GetFont(FontFactory.TIMES, 8, Font.NORMAL);
Font fntverysmallText = FontFactory.GetFont(FontFactory.TIMES, 6, Font.NORMAL);
Font fntBoldheadingText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD);
Font fntparaText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL);
hospt_name = new Phrase("abcd", fntBoldText);
slogan = new Phrase(System.Environment.NewLine + "Quality health care here at home", fntNormalText);
address = new Phrase(System.Environment.NewLine + "P.O. Box 677", fntsmallText);
para.Add(hospt_name);
para.Add(slogan);
para.Add(address);
phr_paitient_name = new Phrase(System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + name + " " + dob, fntNormalText);
pat_name = new Phrase(System.Environment.NewLine + "__________________________________________________________ _______________________________" + System.Environment.NewLine + "Patient's Name D.O.B.", fntsmallText);
pat_det.Add(phr_paitient_name);
pat_det.Add(pat_name);
phr_Consent_For_Treatment_head = new Phrase(System.Environment.NewLine + "Consent For Treatment", fntBoldheadingText);
Consent_For_Treatment_head.Add(phr_Consent_For_Treatment_head);
phr_Consent_For_Treatment = new Phrase("The undersigned consents to procedures and treatments which may be performed during this hospitalization or on an outpatient or emergency basis, including but not limited to anesthesia, laboratory procedures, medical or surgical treatments, x-ray examination, or other services rendered under the general and specific instructions of the physician, physician's assistant, nurse practitioner or Designee. In order to manage accidental exposure of a health care worker to blood or other bodily fluids, the undersigned further consents to such testing; including but not limited to AIDS, TB, Syphilis, and Hepatitis testing, as may be necessary for protection of the heath care worker.", fntparaText);
Consent_For_Treatment.Add(phr_Consent_For_Treatment);
phr_Professional_Care_head = new Phrase(System.Environment.NewLine + "Professional Care", fntBoldheadingText);
Professional_Care_head.Add(phr_Professional_Care_head);
phr_Professional_Care = new Phrase("The attending physician, usually selected by the patient except under unusual or emergency circumstances, is the professional who arranges for the patient's care and treatment Doctors of medicine, including anesthesia provider, pathologists, radiologists, emergency room physicians, osteopathy, podiatry, etc., are independent contractors and are not employees of Val Verde Regional Medical Center. You will receive a separate bill from the physician/anesthesia provider.", fntparaText);
Professional_Care.Add(phr_Professional_Care);
phr_Nursing_Care_head = new Phrase(System.Environment.NewLine + "Nursing Care", fntBoldheadingText);
Nursing_Care_head.Add(phr_Nursing_Care_head);
phr_Nursing_Care = new Phrase("The hospital provides general nursing care. Private duty nursing must be arranged by the patient's representative. The hospital is not responsible for and is released from all liabilities for failure to provide such care.", fntparaText);
Nursing_Care.Add(phr_Nursing_Care);
phr_signtur_line = new Phrase(System.Environment.NewLine + System.Environment.NewLine + "__________________________________________________________________________________________ ________________", fntsmallText);
phr_signtur_bigfont = new Phrase(System.Environment.NewLine + "Signature of Patient/Responsible Party/Patient Representative", fntNormalText);
phr_signtur_smallfont_line = new Phrase("(If patient unable to sign)", fntverysmallText);
phr_signtur_date_line = new Phrase(" Date ", fntNormalText);
signatur.Add(phr_signtur_line);
signatur.Add(phr_signtur_bigfont);
signatur.Add(phr_signtur_smallfont_line);
signatur.Add(phr_signtur_date_line);
phr_relationship = new Phrase(System.Environment.NewLine + "______________________________________________________________" + System.Environment.NewLine + "Relationship to patient", fntNormalText);
relationship.Add(phr_relationship);
phr_witness = new Phrase(System.Environment.NewLine + "___________________________________ __________" + System.Environment.NewLine + "Signature of Witness Date", fntNormalText);
witness.Add(phr_witness);
Document Doc = new Document(PageSize.A4, 0, 0, 25, 50);
PdfWriter.GetInstance(Doc, new FileStream(Server.MapPath("~/abcd/abcd.pdf"), FileMode.Create));
Doc.Open();
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 500f;
table.LockedWidth = true;
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("~/img/abcd.png");
logo.ScaleAbsolute(30, 30);
PdfPCell image_header = new PdfPCell(logo);
image_header.HorizontalAlignment = Element.ALIGN_CENTER;
image_header.BorderWidth = 0;
table.AddCell(image_header);
PdfPCell header = new PdfPCell(para);
header.HorizontalAlignment = Element.ALIGN_CENTER;
header.Colspan = 4;
header.BorderWidth = 0;
table.AddCell(header);
PdfPCell patient = new PdfPCell(pat_det);
patient.BorderWidth = 0;
table.AddCell(patient);
//PdfPCell patientname = new PdfPCell(new Phrase(System.Environment.NewLine + System.Environment.NewLine + "Patient's Name D.O.B."));
//patientname.BorderWidth = 0;
//table.AddCell(patientname);
PdfPCell head_treatment = new PdfPCell(new Phrase(Consent_For_Treatment_head));
head_treatment.BorderWidth = 0;
table.AddCell(head_treatment);
PdfPCell treatment_content = new PdfPCell(Consent_For_Treatment);
treatment_content.BorderWidth = 0;
table.AddCell(treatment_content);
PdfPCell head_profcare = new PdfPCell(Professional_Care_head);
head_profcare.BorderWidth = 0;
table.AddCell(head_profcare);
PdfPCell profcare_content = new PdfPCell(Professional_Care);
profcare_content.BorderWidth = 0;
table.AddCell(profcare_content);
PdfPCell head_nursing = new PdfPCell(Nursing_Care_head);
head_nursing.BorderWidth = 0;
table.AddCell(head_nursing);
PdfPCell nursing_content = new PdfPCell(Nursing_Care);
nursing_content.BorderWidth = 0;
table.AddCell(nursing_content);
PdfPCell sig = new PdfPCell(signatur);
sig.BorderWidth = 0;
table.AddCell(sig);
PdfPCell raltntopatient = new PdfPCell(relationship);
raltntopatient.BorderWidth = 0;
table.AddCell(raltntopatient);
PdfPCell witnesslines = new PdfPCell(witness);
witnesslines.BorderWidth = 0;
table.AddCell(witnesslines);
Doc.Add(table);
Doc.Close();
string path = Server.MapPath("~/abcd/Dabcd.pdf");
ShowPdf(path);
//Response.Redirect(Server.MapPath("~/abcd/abcd.pdf"));
}
and
private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
Response.Flush();
Response.Clear();
}
but the system only down loads one doc..can anyone helpme
If you step back and ignore PDFs for a bit and concentrate on just HTTP requests and responses you should have your answer. When a browser makes an HTTP request (your button click) the server is allowed to send one and only one response. You're code is trying (unsuccessfully) to send multiple responses to the browser. The first time that Response.End is called the pipeline gets terminated actually and the rest of your code doesn't run.
The solution is to just make one giant PDF in one pass, make individual PDFs and merge them or create a zip file containing all of the PDFs.
I guess you should create a zip file that combines your PDF files
If you want to Open the file in new tab you have different Methods:
Method 1:
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
Response.TransmitFile(filePath);
Response.End();
Method 2:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
Hope this helps you!

How to get rid of my "After Spacing" on open xml

In open XML my word document defaults to having "Spacing After: 10 pt" How would I change it to 0, so there is no spacing.
Here is my code, which pretty much grabs the information from a database and places it onto a word document to be able to print out. But the spacing is making the document too big.
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document)) {
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para_main = body.AppendChild(new Paragraph());
Run run_main = para_main.AppendChild(new Run());
// Goes through all of the forms
foreach (var form in forms) {
Table table = new Table();
// Initialize all of the table properties
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 16 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 8 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackSquares), Size = 8 }
),
new SpacingBetweenLines() { Before = "20", After = "20" }
//new TableCellProperties(
// new
//new TableJustification() {Val = TableRowAlignmentValues.Center}
);
table.AppendChild<TableProperties>(tblProp);
Paragraph para_header = body.AppendChild(new Paragraph());
Run run_header = para_header.AppendChild(new Run());
RunProperties runProps = run_header.AppendChild(new RunProperties(new Bold()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header + " | " + username));
for (int i = 0; i < form.FieldList.Count; i++) {
if (!(form.FieldList[i].Token == "USR" || form.FieldList[i].Token == "SNT")) {
TableRow tr = new TableRow();
TableCell header_cell = new TableCell();
header_cell.Append(new Paragraph(new Run(new Text(form.FieldList[i].Label))));
TableCell value_cell = new TableCell();
value_cell.Append(new Paragraph(new Run(new Text(form.FieldList[i].Value))));
tr.Append(header_cell, value_cell);
table.Append(tr);
}
}
wordDoc.MainDocumentPart.Document.Body.Append(table);
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
The line spacing needs to be appended to the paragraph properties and of course that needs to be appended to the paragraph.
Here is the long way to do it. The SpacingBetweenLines can also set the line height and the "rules" control how the before and after values are used.
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
ParagraphProperties paragraphProperties = new ParagraphProperties();
Paragraph paragraph = new Paragraph();
paragraphProperties.Append(spacing);
paragraph.Append(paragraphProperties);
It looks like you are trying to set the line spacing to the table. That will not work that way(believe me I tried). Text around the table is controlled by the text wrapping and the positioning of the table.
Also when working with multiple tables, if you want to keep them separated there needs to be a paragraph(or something other then a table) after the table, otherwise your tables we merge together.
If you need that space create a paragraph with the font set to .5 or something really small and just add it after each table.

Categories

Resources