I need to edit merging PDF's to have a colored bar on each PDF page based on a value in an SQL database where the PDF filename is also stored. I am not great with C# lists but thought perhaps I could build a supplemental list to the iTextSharp "PDFReader" list then when iterating through the PDFReader list write a conditional statement that says "if list 2 value = "Utilities" then create green square" during the PDF merge process.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if ((Session["AccessLevel"].ToString() == "admin") || (Session["AccessLevel"].ToString() == "worker") || (Session["AccessLevel"].ToString() == "client"))
{
if (Request.QueryString["type"] == "QC")
{
//SqlDataSource2.Update();
}
else
{
}
string checkID = Request.QueryString["id"];
SqlDataReader rdr = null;
SqlConnection con2 = new SqlConnection(sqlConnection);
con2.Open();
//string sqlRowCount = "SELECT COUNT(*) FROM [Attachment] WHERE RequestId = '" + checkID + "' AND AttachType != 'Invoice' AND AttachType != 'Cover Sheet' ORDER BY AttachOrder ASC";
sqlUserName2 = "SELECT AttachmentName,AttachType FROM [Attachment] WHERE RequestId = '" + checkID + "' AND AttachType != 'Invoice' AND AttachType != 'Cover Sheet' ORDER BY AttachOrder ASC";
//SqlCommand cmd = new SqlCommand(sqlRowCount, con2);
//string count = cmd.ExecuteScalar().ToString();
SqlCommand cmd2 = new SqlCommand(sqlUserName2, con2);
rdr = cmd2.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
List<PdfReader> readerList = new List<PdfReader>();
List<string> pdfName = new List<string>();
foreach (DataRow row in dt.Rows)
{
PdfReader pdfReader = new PdfReader(Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/uploads/reports/" +
Convert.ToString(row[0])));
readerList.Add(pdfReader);
pdfName.Add(Convert.ToString(row[1]));
//pdfName.Add(rdr["AttachType"].ToString());
}
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Pdf;
Document document = new Document(PageSize.A4, 0, 0, 40, 0);
//Get instance response output stream to write output file.
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
// document.Header = new HeaderFooter(new Phrase("Header Text"), false);
// Parameters passed on to the function that creates the PDF
String headerText = "";
String footerText = "PAGE";
// Define a font and font-size in points (plus f for float) and pick a color
// This one is for both header and footer but you can also create seperate ones
Font fontHeaderFooter = FontFactory.GetFont("arial", 12f);
fontHeaderFooter.Color = Color.BLACK;
// Apply the font to the headerText and create a Phrase with the result
Chunk chkHeader = new Chunk(headerText, fontHeaderFooter);
Phrase p1 = new Phrase(chkHeader);
// create a HeaderFooter element for the header using the Phrase
// The boolean turns numbering on or off
HeaderFooter header = new HeaderFooter(p1, false);
// Remove the border that is set by default
header.Border = Rectangle.NO_BORDER;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = 1;
// add the header to the document
document.Header = header;
// The footer is created in an similar way
// If you want to use numbering like in this example, add a whitespace to the
// text because by default there's no space in between them
if (footerText.Substring(footerText.Length - 1) != " ") footerText += " ";
//string newFooter = footerText + pageCount;
Chunk chkFooter = new Chunk(footerText, fontHeaderFooter);
Phrase p2 = new Phrase(chkFooter);
// Turn on numbering by setting the boolean to true
HeaderFooter footer = new HeaderFooter(p2, true);
footer.Border = Rectangle.NO_BORDER;
footer.Alignment = 1;
document.Footer = footer;
Response.Write(pdfName);
Response.Write("test");
// Open the Document for writing and continue creating its content
document.Open();
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
if ("if list 2 value = "Utilities" then create green square")
{
PdfContentByte cb = writer.DirectContent;
var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
rect.BorderWidth = 5; rect.BorderColor = new BaseColor(2, 3, 0);
cb.Rectangle(rect);
}
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
Response.AppendHeader("content-disposition", "inline; filename=" + Request.QueryString["id"] + "-Final");
Response.ContentType = "application/pdf";
con2.Close();
Response.Write(pdfName);
}
}
catch
{
// Response.Redirect("~/PDFProblem.aspx", false);
}
}
This is a bit clunky but it works until I refactor it. I simply iterated the second list (pdfName) within the first iTextSharp one (pdfReader) using an incrementing integer to move the second list forward when the first list did:
foreach (PdfReader reader in readerList)
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
string totalValue = pdfName[nextOne].ToString();
PdfImportedPage page = writer.GetImportedPage(reader, i);
if (totalValue == "Permit")
{
PdfContentByte cb = writer.DirectContent;
var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
rect.BorderWidth = 5; rect.BorderColor = new BaseColor(2, 3, 0);
cb.Rectangle(rect);
}
if (totalValue == "TaxBill")
{
PdfContentByte cb = writer.DirectContent;
var rect = new iTextSharp.text.Rectangle(200, 200, 100, 100);
rect.Border = iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER;
rect.BorderWidth = 15; rect.BorderColor = new BaseColor(3, 2, 0);
cb.Rectangle(rect);
}
nextOne = nextOne + 1;
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
Related
I have a code to delete file in my folder, but in my line code, I want to delete two file together with different folder. But I always get an error "the process cannot access.... another process". May be you can correct my code and give me a solution. Thanks
1) I have a code to generate watermark when save file(.pdf):
public bool InsertWaterMark(string path)
{
bool valid = true;
string FileDestination = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path;
string FileOriginal = AppDomain.CurrentDomain.BaseDirectory + "Content/" + path.Replace("FileTemporary", "FileOriginal");
System.IO.File.Copy(FileDestination, FileOriginal);
string watermarkText = "Controlled Copy";
#region process
PdfReader reader1 = new PdfReader(FileOriginal);//startFile
using (FileStream fs = new FileStream(FileDestination, FileMode.Create, FileAccess.Write, FileShare.None))//watermarkedFile
{
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
int pageCount1 = reader1.NumberOfPages;
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
for (int i = 1; i <= pageCount1; i++)
{
iTextSharp.text.Rectangle rect = reader1.GetPageSize(i);
PdfContentByte cb = stamper.GetUnderContent(i);
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 80);
PdfGState gState = new PdfGState();
gState.FillOpacity = 0.15f;
cb.SetGState(gState);
cb.SetColorFill(BaseColor.GRAY);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f);
cb.EndText();
PdfContentByte canvas = stamper.GetUnderContent(i);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
canvas.SetColorFill(BaseColor.RED);
PdfGState gStateFooter = new PdfGState();
gStateFooter.FillOpacity = 1f;
canvas.SetGState(gStateFooter);
canvas.BeginText();
canvas.SetFontAndSize(bf, 12);
canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, '"' + "When printed, this documents are considered uncontrolled" + '"', 300.7f, 10.7f, 0);
canvas.EndText();
cb.EndLayer();
}
}
}
#endregion
return valid;
}
2) And this code i call when delete detail data from one page together.
public ActionResult Delete(string parm)
{
TableEDIS data = db.TableEDISs.FirstOrDefault(e => e.detail_guid_edis == new Guid(parm));
string fisikFile = data.upload_document;
string fisikFileFormulir = data.upload_document_formulir;
if (!string.IsNullOrEmpty(fisikFile))
{
var relativePath = "~/Content/" + fisikFile;
var absolutePath = HttpContext.Server.MapPath(relativePath);
var absolutePathOriginal = HttpContext.Server.MapPath(relativePath.Replace("Temporary", "Original"));
if (Directory.Exists(Path.GetDirectoryName(absolutePath)))
{
System.IO.File.Delete(absolutePath);
}
if (Directory.Exists(Path.GetDirectoryName(absolutePathOriginal)))
{
System.IO.File.Delete(absolutePathOriginal);
}
}
}
I hope you understand what I mean.
Thanks in advance.
My spidey senses tells me you need to call
reader1.Close();
I am using NPOI to export the data to excel. I am forcing the file to be downloaded as an attachment for the user. When the user saves the file on the disk and opens the file it works but fails when he tries to select the open option from the download dialog box. Please see the code below. Not sure what is wrong
var xssfworkbook = new XSSFWorkbook();
var sheet1 = xssfworkbook.CreateSheet("Sheet 1");
//make header row
var row1 = sheet1.CreateRow(0);
var cell0 = row1.CreateCell(0);
cell0.SetCellValue("Firm Id");
var cell1 = row1.CreateCell(1);
cell1.SetCellValue("Account Number");
for (int i = 0; i < result.Count; i++)
{
var row = sheet1.CreateRow(i + 1);
if (result[i].FeeAmount != null)
{
var cellFirmID = row.CreateCell(0);
cellFirmID.SetCellValue(result[i].FirmID);
}
if (result[i].AccountNumber != null)
{
var cellAccountNumber = row.CreateCell(1);
cellAccountNumber.SetCellValue(result[i].AccountNumber);
}
}
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "BESTINVEST_fee_rebate_loader_.xlsx"));
MemoryStream file = WriteToStream(xssfworkbook);
response.Clear();
response.BinaryWrite(file.ToArray());
response.End();
private MemoryStream WriteToStream(XSSFWorkbook xssfworkbook)
{
MemoryStream file = new MemoryStream();
xssfworkbook.Write(file);
return file;
}
This problem is from "culture". before Create excel:
var culture=new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture=culture;
Thread.CurrentThread.CurrentUICulture=culture;
I would recommend you make sure your cells are unlocked.
I use the following without problems:
var workbook = new XSSFWorkbook();
var members = (obj as IEnumerable<MemberListViewModel>).ToDataSourceResult(request).Data;
var sheet = workbook.CreateSheet(TempData["List"].ToString());
var headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Name");
headerRow.CreateCell(1).SetCellValue("Degrees");
headerRow.CreateCell(2).SetCellValue("Rank");
headerRow.CreateCell(3).SetCellValue("Endowed Professorship");
headerRow.CreateCell(4).SetCellValue("Department");
headerRow.CreateCell(5).SetCellValue("Program");
var font = workbook.CreateFont();
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
style.SetFont(font);
style.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
style.IsLocked = false;
style.WrapText = true;
for (int i = 0; i < 6; i++)
{
var colStyle = sheet.GetColumnStyle(i);
colStyle.WrapText = !colStyle.WrapText;
sheet.SetDefaultColumnStyle(i, colStyle);
var cell = headerRow.Cells[i];
cell.CellStyle = style;
}
headerRow.RowStyle = style;
sheet.SetColumnWidth(0, 30 * 256);
sheet.SetColumnWidth(1, 20 * 256);
sheet.SetColumnWidth(2, 20 * 256);
sheet.SetColumnWidth(3, 50 * 256);
sheet.SetColumnWidth(4, 30 * 256);
sheet.SetColumnWidth(5, 50 * 256);
int rowNumber = 1;
style = (XSSFCellStyle)workbook.CreateCellStyle();
style.IsLocked = false;
style.WrapText = true;
foreach (MemberListViewModel member in members)
{
var row = sheet.CreateRow(rowNumber++);
row.CreateCell(0).SetCellValue(member.FullName);
row.CreateCell(1).SetCellValue(member.degrees);
row.CreateCell(2).SetCellValue(member.rank);
row.CreateCell(3).SetCellValue(member.endowed_professorship);
row.CreateCell(4).SetCellValue(member.department);
row.CreateCell(5).SetCellValue(member.program);
}
//var colStyle = sheet.GetColumnStyle(3);
//colStyle.WrapText = !colStyle.WrapText;
//sheet.SetDefaultColumnStyle(3, colStyle);
workbook.Write(output);
var fileName = String.Format(
"{0} {2} - {1}.xlsx",
DateTime.Now.ToString("yyyyMMdd-HHmmss"),
Utilities.getUsername(Utilities.GetCurrentUser()), TempData["List"]).Replace(":", "");
var file = File(output.ToArray(), Utilities.ExcelFileContentType, fileName);
var context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.AddHeader("content-disposition", String.Format("inline;filename=\'{0}\'", fileName));
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = file.ContentType;
context.Response.AddHeader("content-length", file.FileContents.Length.ToString());
context.Response.BinaryWrite(buffer: file.FileContents.ToArray());
context.Response.Flush();
context.Response.End();
output.Dispose();
I was wondering how would it be possible to split the word document into two columns. The reason why I want to do this is because I want to be able to fit all of the information on one page.
Thank you so much for your help and time!
My Code
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var margin_size = 100;
PageMargin pargeMargins = new PageMargin();
pargeMargins.Top = margin_size;
pargeMargins.Bottom = margin_size;
SectionProperties sectionProps = new SectionProperties();
sectionProps.Append(pargeMargins);
Body body = mainPart.Document.AppendChild(new Body());
body.Append(sectionProps);
ParagraphProperties paragraphProperties = new ParagraphProperties
(
//new ParagraphStyleId() { Val = "No Spacing" },
new SpacingBetweenLines() { After = "0" }
);
Paragraph para_main = body.AppendChild(new Paragraph(paragraphProperties));
// Creating the Header where the Serial Number will exist
// Serial Number
Run run_mainHeader = para_main.AppendChild(new Run());
RunProperties runProp_mainHeader = new RunProperties(); // Create run properties.
FontSize size_mainHeader = new FontSize();
size_mainHeader.Val = new StringValue("48");
runProp_mainHeader.Append(size_mainHeader);
run_mainHeader.Append(runProp_mainHeader); // Append all of the properties
run_mainHeader.Append(new Text("S/N: " + sn));
// Serial Barcode
Run run_barcode = para_main.AppendChild(new Run());
RunProperties runProp_barcode = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode = new RunFonts(); // Create font
runFontMain_barcode.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode = new FontSize();
size_barcode.Val = new StringValue("48");
runProp_barcode.Append(runFontMain_barcode);
runProp_barcode.Append(size_barcode);
run_barcode.PrependChild<RunProperties>(runProp_barcode);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode.AppendChild(new Text("*" + sn + "*"));
run_barcode.AppendChild(new Break());
// Tube Type
Run run_tubetype = para_main.AppendChild(new Run());
RunProperties runProp_tubetype = new RunProperties(); // Create run properties.
FontSize size_tubetype = new FontSize();
size_tubetype.Val = new StringValue("38");
runProp_tubetype.Append(size_tubetype);
run_tubetype.Append(runProp_tubetype); // Append all of the properties
run_tubetype.Append(new Text("Tube Type: " + forms[0].TubeType + " "));
//run_tubetype.Append(new Break());
// Tube Barcode
Run run_barcode_tube = para_main.AppendChild(new Run());
RunProperties runProp_barcode_tube = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode_tube = new RunFonts(); // Create font
runFontMain_barcode_tube.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode_tube = new FontSize();
size_barcode_tube.Val = new StringValue("48");
runProp_barcode_tube.Append(runFontMain_barcode_tube);
runProp_barcode_tube.Append(size_barcode_tube);
run_barcode_tube.PrependChild<RunProperties>(runProp_barcode_tube);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode_tube.AppendChild(new Text("*" + forms[0].TubeType + "*"));
run_barcode_tube.AppendChild(new Break());
// Goes through all of the forms
foreach (var form in forms)
{
// Set up a header per form
Run run_header = para_main.AppendChild(new Run());
RunProperties runProp_formHeader = new RunProperties();
Bold bold = new Bold();
Underline ul = new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single };
FontSize size_formHeader = new FontSize();
size_formHeader.Val = new StringValue("24");
runProp_formHeader.Append(size_formHeader);
runProp_formHeader.Append(bold);
runProp_formHeader.Append(ul);
run_header.AppendChild(new RunProperties(runProp_formHeader));
//run_header.AppendChild(new RunProperties(new Bold(), new Underline()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header));
run_header.AppendChild(new Break());
// Goes through all of the fields that each form contains.
for (int i = 0; i < form.FieldList.Count; i++)
{
// Do not need to print out user or serial for each form.
if (!(form.FieldList[i].Token == "SNT"))
{
Run run_data = para_main.AppendChild(new Run());
if (form.FieldList[i].Default)
{
run_data.AppendChild(new Text(form.FieldList[i].Label));
}
else
{
run_data.AppendChild(new Text(form.FieldList[i].Label + " " + form.FieldList[i].Spec + form.FieldList[i].Value));
}
run_data.AppendChild(new Break());
}
}
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
Currently the code prints out everything top-down on one column. And I want it with two columns
You can two or how many columns you want using the Columns Class for the SectionProperties and ParagraphProperties Class
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.columns(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.paragraphproperties(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sectionproperties(v=office.14).aspx
This should do it:
// Add a new main document part.
package.AddMainDocumentPart();
// Create the Document DOM.
package.MainDocumentPart.Document = new Document();
Body bd = package.MainDocumentPart.Document.Body = new Body();
//write a first paragraph on two columns
var paragrap1 = new Paragraph();
var paragraphSectionProperties = new ParagraphProperties(new SectionProperties());
var paragraphColumns = new Columns();
paragraphColumns.EqualWidth = true;
paragraphColumns.ColumnCount = 2;
paragraphSectionProperties.Append(paragraphColumns);
paragrap1.Append(paragraphSectionProperties);
paragrap1.Append(new Run(new Text(str)));
bd.AppendChild(paragrap1);
//write another paragraph without paragraph properties
bd.Append(new Paragraph(new Run(new Text(str))));
//set the body properties default three columns
var sectionProperties = new SectionProperties();
var columns = new Columns();
columns.EqualWidth = true;
columns.ColumnCount = 3;
sectionProperties.Append(columns);
bd.Append(sectionProperties);
package.MainDocumentPart.Document.Save();
You can do it for the complete document with this code:
var sectionProperty = document.Body.Descendants<SectionProperties>().First();
var paragraphColumns = new Columns {EqualWidth = true, ColumnCount = 2};
sectionProperty.Append(paragraphColumns);
Try with..
Word.Application WordApp = new Word.Application();
Word.Document BaseDoc = default(Word.Document);
Word.Document DestDoc = default(Word.Document);
int intNumberOfPages = 0;
string intNumberOfChars = null;
int intPage = 0;
//Word Constants
const var wdGoToPage = 1;
const var wdStory = 6;
const var wdExtend = 1;
const var wdCharacter = 1;
//Show WordApp
WordApp.ShowMe();
//Load Base Document
BaseDoc = WordApp.Documents.Open(Filename);
BaseDoc.Repaginate();
//Loop through pages
intNumberOfPages = BaseDoc.BuiltInDocumentProperties("Number of Pages").value;
intNumberOfChars = BaseDoc.BuiltInDocumentProperties("Number of Characters").value;
for (intPage = 1; intPage <= intNumberOfPages; intPage++) {
if (intPage == intNumberOfPages) {
WordApp.Selection.EndKey(wdStory); }
else {
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.MoveLeft(Unit = wdCharacter, Count = 1);
}
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Copy();
Application.DoEvents();
//Create New Document
DestDoc = WordApp.Documents.Add;
DestDoc.Activate();
WordApp.Selection.Paste();
DestDoc.SaveAs(NewFileName + intPage.ToString + ".doc");
DestDoc.Close();
DestDoc = null;
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Delete();
Application.DoEvents();
}
BaseDoc.Close(false);
BaseDoc = null;
WordApp.Quit();
WordApp = null;
How would I align my table in the middle of the word document in open xml?
Here is my code and I want to align the table in the middle.
Here is my code. I'm trying to use TableJustification, but it seems like its not working
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Run run = 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 }
)
);
// Align the table to the center
TableJustification justs_center = new TableJustification() { Val = _____ };
table.AppendChild(justs_center);
table.AppendChild<TableProperties>(tblProp);
Paragraph para = body.AppendChild(new Paragraph());
Run run_header = para.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 + ": " + form.FieldList[i].Value))));
tr.Append(header_cell);
table.Append(tr);
}
}
wordDoc.MainDocumentPart.Document.Body.Append(table);
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
}
Table t = new Table(
new TableProperties(
...
new TableJustification() { Val = TableRowAlignmentValues.Center},
...),
new TableRow(...),
);
Trying to center the table with the accepted answer did not seem to work. I needed to apply the center justification to all of the rows as well
var t = new Table();
var tableProps = new TableProperties();
tableProps.TableJustification = new TableJustification { Val = TableRowAlignmentValues.Center };
t.Append(tableProps);
var row = new TableRow();
var rowProps = new TableRowProperties();
rowProps.Append(new TableJustification { Val = TableRowAlignmentValues.Center });
row.Append(rowProps);
Found using the Open XML Productivity Tool
Actually, you need to apply the center justification to all rows in TableRowProperties only. Even if you don't apply justification in TableProperties, the table will be centered anyway. And I'm interested to find out what is the purpose of justification in TableRowProperties if someone knows.
Well i'm trying to merge multiple PDFs in to one.
I gives no errors while compiling. I tried to merge the docs first but that went wrong because I'm working with tables.
This is the asp.net code-behind
if (Button.Equals("PreviewWord")) {
String eventTemplate = Server.MapPath("/ERAS/Badges/Template/EventTemp" + EventName + ".doc");
String SinglePreview = Server.MapPath("/ERAS/Badges/Template/PreviewSingle" + EventName + ".doc");
String PDFPreview = Server.MapPath("/ERAS/Badges/Template/PDFPreviewSingle" + EventName + ".pdf");
String previewPDFs = Server.MapPath("/ERAS/Badges/Template/PreviewPDFs" + EventName + ".pdf");
if (System.IO.File.Exists((String)eventTemplate))
{
if (vulGegevensIn == true)
{
//This creates a Worddocument and fills in names etc from database
CreateWordDocument(vulGegevensIn, eventTemplate, SinglePreview, false);
//This saves the SinglePreview.doc as a PDF #param place of PDFPreview
CreatePDF(SinglePreview, PDFPreview);
//Trying to merge
String[] previewsSmall=new String[1];
previewsSmall[0] = PDFPreview;
PDFMergenITextSharp.MergeFiles(previewPDFs, previewsSmall);
}
// merge PDFs here...........................;
//here
//no here//
//...
} }
This is the PDFMergenITextSharpClass
public static class PDFMergenITextSharp
{
public static void MergeFiles(string destinationFile, string[] sourceFiles)
{
try
{
int f = 0;
// we create a reader for a certain document
PdfReader reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
// step 4: we add content
while (f < sourceFiles.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
//Console.WriteLine("Processed page " + i);
}
f++;
if (f < sourceFiles.Length)
{
reader = new PdfReader(sourceFiles[f]);
// we retrieve the total number of pages
n = reader.NumberOfPages;
//Console.WriteLine("There are " + n + " pages in the original file.");
}
}
// step 5: we close the document
document.Close();
}
catch (Exception e)
{
string strOb = e.Message;
}
}
public static int CountPageNo(string strFileName)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(strFileName);
// we retrieve the total number of pages
return reader.NumberOfPages;
}
}
I found the answer:
Instead of the 2nd Method, add more files to the first array of input files.
public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
// step 1: creation of a document-object
Document document = new Document();
//create newFileStream object which will be disposed at the end
using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
{
// step 2: we create a writer that listens to the document
PdfCopy writer = new PdfCopy(document, newFileStream);
// step 3: we open the document
document.Open();
foreach (string fileName in fileNames)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(fileName);
reader.ConsolidateNamedDestinations();
// step 4: we add content
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
}
PRAcroForm form = reader.AcroForm;
if (form != null)
{
writer.CopyAcroForm(reader);
}
reader.Close();
}
// step 5: we close the document and writer
writer.Close();
document.Close();
}//disposes the newFileStream object
}
I found a very nice solution on this site : http://weblogs.sqlteam.com/mladenp/archive/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5.aspx
I update the method in this mode :
public static bool MergePdfs(IEnumerable<string> fileNames, string targetFileName)
{
bool success = true;
using (FileStream stream = new(targetFileName, FileMode.Create))
{
Document document = new();
PdfCopy pdf = new(document, stream);
PdfReader? reader = null;
try
{
document.Open();
foreach (string file in fileNames)
{
reader = new PdfReader(file);
pdf.AddDocument(reader);
reader.Close();
}
}
catch (Exception)
{
success = false;
reader?.Close();
}
finally
{
document?.Close();
}
}
return success;
}
Code For Merging PDF's in Itextsharp
public static void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
//fixed typo
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
File.Delete(file);
});
}
}
Using iTextSharp.dll
protected void Page_Load(object sender, EventArgs e)
{
String[] files = #"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
MergeFiles(#"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
}
}
Response.Write("Success");
document.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
Merge byte arrays of multiple PDF files:
public static byte[] MergePDFs(List<byte[]> pdfFiles)
{
if (pdfFiles.Count > 1)
{
PdfReader finalPdf;
Document pdfContainer;
PdfWriter pdfCopy;
MemoryStream msFinalPdf = new MemoryStream();
finalPdf = new PdfReader(pdfFiles[0]);
pdfContainer = new Document();
pdfCopy = new PdfSmartCopy(pdfContainer, msFinalPdf);
pdfContainer.Open();
for (int k = 0; k < pdfFiles.Count; k++)
{
finalPdf = new PdfReader(pdfFiles[k]);
for (int i = 1; i < finalPdf.NumberOfPages + 1; i++)
{
((PdfSmartCopy)pdfCopy).AddPage(pdfCopy.GetImportedPage(finalPdf, i));
}
pdfCopy.FreeReader(finalPdf);
}
finalPdf.Close();
pdfCopy.Close();
pdfContainer.Close();
return msFinalPdf.ToArray();
}
else if (pdfFiles.Count == 1)
{
return pdfFiles[0];
}
return null;
}
I don't see this solution anywhere and supposedly ... according to one person, the proper way to do it is with copyPagesTo(). This does work I tested it. Your mileage may vary between city and open road driving. Goo luck.
public static bool MergePDFs(List<string> lststrInputFiles, string OutputFile, out int iPageCount, out string strError)
{
strError = string.Empty;
PdfWriter pdfWriter = new PdfWriter(OutputFile);
PdfDocument pdfDocumentOut = new PdfDocument(pdfWriter);
PdfReader pdfReader0 = new PdfReader(lststrInputFiles[0]);
PdfDocument pdfDocument0 = new PdfDocument(pdfReader0);
int iFirstPdfPageCount0 = pdfDocument0.GetNumberOfPages();
pdfDocument0.CopyPagesTo(1, iFirstPdfPageCount0, pdfDocumentOut);
iPageCount = pdfDocumentOut.GetNumberOfPages();
for (int ii = 1; ii < lststrInputFiles.Count; ii++)
{
PdfReader pdfReader1 = new PdfReader(lststrInputFiles[ii]);
PdfDocument pdfDocument1 = new PdfDocument(pdfReader1);
int iFirstPdfPageCount1 = pdfDocument1.GetNumberOfPages();
iPageCount += iFirstPdfPageCount1;
pdfDocument1.CopyPagesTo(1, iFirstPdfPageCount1, pdfDocumentOut);
int iFirstPdfPageCount00 = pdfDocumentOut.GetNumberOfPages();
}
pdfDocumentOut.Close();
return true;
}
Please also visit and read this article where I explained everything in detail about How to Merge Multiple PDF Files Into Single PDF Using Itextsharp in C#
Implementation:
try
{
string FPath = "";
// Create For loop for get/create muliple report on single click based on row of gridview control
for (int j = 0; j < Gridview1.Rows.Count; j++)
{
// Return datatable for data
DataTable dtDetail = new My_GlobalClass().GetDataTable(Convert.ToInt32(Gridview1.Rows[0]["JobId"]));
int i = Convert.ToInt32(Gridview1.Rows[0]["JobId"]);
if (dtDetail.Rows.Count > 0)
{
// Create Object of ReportDocument
ReportDocument cryRpt = new ReportDocument();
//Store path of .rpt file
string StrPath = Application.StartupPath + "\\RPT";
StrPath = StrPath + "\\";
StrPath = StrPath + "rptCodingvila_Articles_Report.rpt";
cryRpt.Load(StrPath);
// Assign Report Datasource
cryRpt.SetDataSource(dtDetail);
// Assign Reportsource to Report viewer
CryViewer.ReportSource = cryRpt;
CryViewer.Refresh();
// Store path/name of pdf file one by one
string StrPathN = Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report" + i.ToString() + ".Pdf";
FPath = FPath == "" ? StrPathN : FPath + "," + StrPathN;
// Export Report in PDF
cryRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, StrPathN);
}
}
if (FPath != "")
{
// Check for File Existing or Not
if (System.IO.File.Exists(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"))
System.IO.File.Delete(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Split and store pdf input file
string[] files = FPath.Split(',');
// Marge Multiple PDF File
MargeMultiplePDF(files, Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Open Created/Marged PDF Output File
Process.Start(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
// Check and Delete Input file
foreach (string item in files)
{
if (System.IO.File.Exists(item.ToString()))
System.IO.File.Delete(item.ToString());
}
}
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Create Function for Marge PDF
public static void MargeMultiplePDF(string[] PDFfileNames, string OutputFile)
{
iTextSharp.text.Document PDFdoc = new iTextSharp.text.Document();
using (System.IO.FileStream MyFileStream = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create))
{
iTextSharp.text.pdf.PdfCopy PDFwriter = new iTextSharp.text.pdf.PdfCopy(PDFdoc, MyFileStream);
if (PDFwriter == null)
{
return;
}
PDFdoc.Open();
foreach (string fileName in PDFfileNames)
{
iTextSharp.text.pdf.PdfReader PDFreader = new iTextSharp.text.pdf.PdfReader(fileName);
PDFreader.ConsolidateNamedDestinations();
for (int i = 1; i <= PDFreader.NumberOfPages; i++)
{
iTextSharp.text.pdf.PdfImportedPage page = PDFwriter.GetImportedPage(PDFreader, i);
PDFwriter.AddPage(page);
}
iTextSharp.text.pdf.PRAcroForm form = PDFreader.AcroForm;
if (form != null)
{
PDFwriter.CopyAcroForm(PDFreader);
}
PDFreader.Close();
}
PDFwriter.Close();
PDFdoc.Close();
}
}