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.
Related
I have a word document where I add three paragraphs. I want to add three paragraphs in one line not like is displaying now in different lines like this:
text1
text2
text3.
I want to be text1,text2,text3.
Here is my code:
using(WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
{
gjenerimi = randomstring(14);
var body = wDoc.MainDocumentPart.Document.Body;
var lastParagraf = body.Elements < Paragraph > ().FirstOrDefault();
var newParagraf2 = new Paragraph(new Run(new Text(DateTime.Now.ToString())));
var newParagraf3 = new Paragraph(new Run(new Text(gjenerimi)));
var newParagraf4 = new Paragraph(new Run(new Text(merreshifren())));
lastParagraf.InsertAfterSelf(newParagraf2);
lastParagraf.InsertAfterSelf(newParagraf3);
lastParagraf.InsertAfterSelf(newParagraf4);
}
Can anyone help me please?
If you don't want paragraphs, don't use paragraphs:
using(WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
{
var gjenerimi = randomstring(14);
var body = wDoc.MainDocumentPart.Document.Body;
var lastParagraf = body.Elements<Paragraph>().FirstOrDefault();
var run = new Run();
run.AppendChild(new Text(DateTime.Now.ToString()));
run.AppendChild(new Text(gjenerimi));
run.AppendChild(new Text(merreshifren()));
lastParagraf.AppendChild(run);
}
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);
I'm trying to add a table to the PDF file I'm generating. I can add stuff "directly" but want to put the various paragraphs or phrases in table cells to get everything to align nicely.
The following code should add three paragraphs "free-form" first, then the same three in a table. However, only the first three display - the table is nowhere to be seen. Here's the code:
try
{
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
var titleFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.BLACK);
var docTitle = new Paragraph("UCSC Direct - Direct Payment Form", titleFont);
doc.Add(docTitle);
var subtitleFont = FontFactory.GetFont("Times Roman", 9, BaseColor.BLACK);
var subTitle = new Paragraph("(not to be used for reimbursement of services)", subtitleFont);
doc.Add(subTitle);
var importantNoticeFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
var importantNotice = new Paragraph("Important: Form must be filled out in Adobe Reader or Acrobat Professional 8.1 or above. To save completed forms, Acrobat Professional is required. For technical and accessibility assistance, contact the Campus Controller's Office.", importantNoticeFont);
importantNotice.Leading = 0;
importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings
importantNotice.ExtraParagraphSpace = 4; // ? test this....
doc.Add(importantNotice);
// Add a table
PdfPTable table = new PdfPTable(10); // the arg is the number of columns
// Row 1
PdfPCell cell = new PdfPCell(docTitle);
cell.Colspan = 3;
cell.BorderWidth = 0;
//cell.BorderColor = BaseColor.WHITE; <= this works for me, but if background is something other than white, it wouldn't
cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
// Row 2
PdfPCell cellCaveat = new PdfPCell(subTitle);
cellCaveat.Colspan = 2;
cellCaveat.BorderWidth = 0;
table.AddCell(cellCaveat);
// Row 3
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.Colspan = 5;
cellImportantNote.BorderWidth = 0;
table.AddCell(importantNotice);
doc.Add(table);
doc.Close();
}
var bytes = ms.ToArray();
String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
File.WriteAllBytes(testFile, bytes);
MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
}
}
}
catch (DocumentException dex)
{
throw (dex);
}
catch (IOException ioex)
{
throw (ioex);
}
catch (Exception ex)
{
String exMsg = ex.Message;
MessageBox.Show(String.Format("Boo-boo!: {0}", ex.Message));
}
Why is my borderless table invisible or nonexistant?
UPDATE
Based on Bruno's answer, and applying it to the output that I really need, this works:
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4, 50, 50, 25, 25)) {
//Create a writer that's bound to our PDF abstraction and our stream
using (var writer = PdfWriter.GetInstance(doc, ms))
{
//Open the document for writing
doc.Open();
// Mimic the appearance of Direct_Payment.pdf
var courierBold11Font = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.BLACK);
var docTitle = new Paragraph("UCSC - Direct Payment Form", courierBold11Font);
doc.Add(docTitle);
var timesRoman9Font = FontFactory.GetFont("Times Roman", 9, BaseColor.BLACK);
var subTitle = new Paragraph("(not to be used for reimbursement of services)", timesRoman9Font);
doc.Add(subTitle);
var courier9RedFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
var importantNotice = new Paragraph("Important: Form must be filled out in Adobe Reader or Acrobat Professional 8.1 or above. To save completed forms, Acrobat Professional is required. For technical and accessibility assistance, contact the Campus Controller's Office.", courier9RedFont);
importantNotice.Leading = 0;
importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings
// Add a table
PdfPTable table = new PdfPTable(1);
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.BorderWidth = PdfPCell.NO_BORDER;
table.WidthPercentage = 50;
table.HorizontalAlignment = Element.ALIGN_LEFT;
table.AddCell(cellImportantNote);
doc.Add(table);
doc.Close();
}
var bytes = ms.ToArray();
String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
File.WriteAllBytes(testFile, bytes);
MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
}
}
Please take a look at the SimpleTable7 example and compare the Java code with your [?] code:
This part is relevant:
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.setColspan(5);
cellImportantNote.setBorder(PdfPCell.NO_BORDER);
table.addCell(cellImportantNote);
If I would convert your [?] code to Java, you'd have:
PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.setColspan(5);
cellImportantNote.setBorder(PdfPCell.NO_BORDER);
table.addCell(importantNotice);
Do you see the difference? You create a cellImportantNote instance, but you aren't using it anywhere. Instead of adding cellImportantNote to the table, you add the importantNotice paragraph.
This means that you are creating a table with 10 columns that has a single row of which only 6 cells are taken (because you have 1 cell with colspan 3, 1 cell with colspan 2 and 1 cell with colspan 1).
By default, iText doesn't render any rows that aren't complete, and since your table doesn't have any complete row, the table isn't being rendered.
If you look at the resulting PDF, simple_table7.pdf, you'll notice that I also added a second table. This table has only three columns, but it looks identical to the table you constructed. Instead of improper use of the colspan functionality, I defined relative widths for the three columns:
table = new PdfPTable(3);
table.setWidths(new int[]{3, 2, 5});
cell.setColspan(1);
table.addCell(cell);
cellCaveat.setColspan(1);
table.addCell(cellCaveat);
cellImportantNote.setColspan(1);
table.addCell(cellImportantNote);
document.add(table);
Note that I also avoid to use meaningless numbers. For instance, instead of:
cell.setHorizontalAlignment(0); // 0 means left
I use:
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
This way, people can read what this line means without having to depend on comments.
Furtermore, I replaced:
cell.setBorderWidth(0);
with:
cell.setBorder(PdfPCell.NO_BORDER);
That too, is only a matter of taste, but I think it's important if you want to keep your code maintainable.
I've been working on my site, and trying to create an Export to Word. The export works well, converting HTML string to DOCX.
I'm trying to figure out how I can adjust the Line Spacing. By Default Word is adding 8pt Spacing After and setting the Line Spacing to double. I would prefer 0 and Single.
Here is the Function I created to Save a Word Document:
private static void SaveDOCX(string fileName, string BodyText, bool isLandScape, double rMargin, double lMargin, double bMargin, double tMargin)
{
string htmlSectionID = "Sect1";
//Creating a word document using the the Open XML SDK 2.0
WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document);
//create a paragraph
MainDocumentPart mainDocumenPart = document.AddMainDocumentPart();
mainDocumenPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
Body documentBody = new Body();
mainDocumenPart.Document.Append(documentBody);
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>" + BodyText + "</body></html>"));
// Create alternative format import part.
AlternativeFormatImportPart formatImportPart = mainDocumenPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, htmlSectionID);
//ms.Seek(0, SeekOrigin.Begin);
// Feed HTML data into format import part (chunk).
formatImportPart.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = htmlSectionID;
mainDocumenPart.Document.Body.Append(altChunk);
/*
inch equiv = 1440 (1 inch margin)
*/
double width = 8.5 * 1440;
double height = 11 * 1440;
SectionProperties sectionProps = new SectionProperties();
PageSize pageSize;
if (isLandScape)
{
pageSize = new PageSize() { Width = (UInt32Value)height, Height = (UInt32Value)width, Orient = PageOrientationValues.Landscape };
}
else
{
pageSize = new PageSize() { Width = (UInt32Value)width, Height = (UInt32Value)height, Orient = PageOrientationValues.Portrait };
}
rMargin = rMargin * 1440;
lMargin = lMargin * 1440;
bMargin = bMargin * 1440;
tMargin = tMargin * 1440;
PageMargin pageMargin = new PageMargin() { Top = (Int32)tMargin, Right = (UInt32Value)rMargin, Bottom = (Int32)bMargin, Left = (UInt32Value)lMargin, Header = (UInt32Value)360U, Footer = (UInt32Value)360U, Gutter = (UInt32Value)0U };
sectionProps.Append(pageSize);
sectionProps.Append(pageMargin);
mainDocumenPart.Document.Body.Append(sectionProps);
//Saving/Disposing of the created word Document
document.MainDocumentPart.Document.Save();
document.Dispose();
}
In searching, I found this code:
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
I've placed it many places in my function, but I can't seem to find the correct place to Append this setting.
I worked on the function trying to set the spacing in code, but wasn't able to remove the spacing. I decided to try creating a Template Word Document and setting the spacing in that document.
I copy the template.docx file, creating the one I will use, then use the adjusted function below to add the HTML string:
private static void SaveDOCX(string fileName, string BodyText, bool isLandScape, double rMargin, double lMargin, double bMargin, double tMargin)
{
WordprocessingDocument document = WordprocessingDocument.Open(fileName, true);
MainDocumentPart mainDocumenPart = document.MainDocumentPart;
//Place the HTML String into a MemoryStream Object
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>" + BodyText + "</body></html>"));
//Assign an HTML Section for the String Text
string htmlSectionID = "Sect1";
// Create alternative format import part.
AlternativeFormatImportPart formatImportPart = mainDocumenPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, htmlSectionID);
// Feed HTML data into format import part (chunk).
formatImportPart.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = htmlSectionID;
//Clear out the Document Body and Insert just the HTML string. (This prevents an empty First Line)
mainDocumenPart.Document.Body.RemoveAllChildren();
mainDocumenPart.Document.Body.Append(altChunk);
/*
Set the Page Orientation and Margins Based on Page Size
inch equiv = 1440 (1 inch margin)
*/
double width = 8.5 * 1440;
double height = 11 * 1440;
SectionProperties sectionProps = new SectionProperties();
PageSize pageSize;
if (isLandScape)
pageSize = new PageSize() { Width = (UInt32Value)height, Height = (UInt32Value)width, Orient = PageOrientationValues.Landscape };
else
pageSize = new PageSize() { Width = (UInt32Value)width, Height = (UInt32Value)height, Orient = PageOrientationValues.Portrait };
rMargin = rMargin * 1440;
lMargin = lMargin * 1440;
bMargin = bMargin * 1440;
tMargin = tMargin * 1440;
PageMargin pageMargin = new PageMargin() { Top = (Int32)tMargin, Right = (UInt32Value)rMargin, Bottom = (Int32)bMargin, Left = (UInt32Value)lMargin, Header = (UInt32Value)360U, Footer = (UInt32Value)360U, Gutter = (UInt32Value)0U };
sectionProps.Append(pageSize);
sectionProps.Append(pageMargin);
mainDocumenPart.Document.Body.Append(sectionProps);
//Saving/Disposing of the created word Document
document.MainDocumentPart.Document.Save();
document.Dispose();
}
By using the template file, the line spacing is correct.
For those that might find this function useful, here is the code that calls the function:
string filePath = "~/Content/Exports/Temp/";
string WordTemplateFile = HttpContext.Current.Server.MapPath("/Content/Templates/WordTemplate.docx");
string DestinationPath = HttpContext.Current.Server.MapPath(filePath);
string NewFileName = DOCXFileName + ".docx";
string destFile = System.IO.Path.Combine(DestinationPath, NewFileName);
System.IO.File.Copy(WordTemplateFile, destFile, true);
SaveDOCX(destFile, HTMLString, isLandScape, rMargin, lMargin, bMargin, tMargin);
You can't change the formatting because your code is only inserting HTML into a Word doc. To change the formatting, the HTML text needs to be converted to regular text and added to the Word doc as such. I was in a similar issue and using the HtmlToOpenXml library makes this quick and simple.
using HtmlToOpenXml;
Then the function:
protected virtual void createWord()
{
string html = "*myHtml*";
// Create WordProcessingDocument
WordprocessingDocument doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = doc.MainDocumentPart;
if (mainPart == null)
mainPart = doc.AddMainDocumentPart();
Document document = doc.MainDocumentPart.Document;
if (document == null)
document = mainPart.Document = new Document();
Body body = mainPart.Document.Body;
if (body == null)
body = mainPart.Document.Body = new Body(new SectionProperties(new PageMargin() { Top = 1440, Right = 1440U, Bottom = 1440, Left = 1440U, Header = 720U, Footer = 720U, Gutter = 0U }));
// Convert Html to OpenXml
HtmlConverter converter = new HtmlConverter(mainPart);
converter.ParseHtml(html);
// Reformat paragraphs
ParagraphProperties pProps = new ParagraphProperties(new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" });
var paragraphs = doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().ToList();
foreach (Paragraph p in paragraphs)
{
if (p != null)
p.PrependChild(pProps.CloneNode(true));
}
// Close the document handle
doc.Close();
}
I have a class that build the content for my table of contents and that works, fine and dandy.
Here's the code:
public void Build(string center,IDictionary<string,iTextSharp.text.Image> images)
{
iTextSharp.text.Image image = null;
XPathDocument rapportTekst = new XPathDocument(Application.StartupPath + #"..\..\..\RapportTemplates\RapportTekst.xml");
XPathNavigator nav = rapportTekst.CreateNavigator();
XPathNodeIterator iter;
iter = nav.Select("//dokument/brevhoved");
iter.MoveNext();
var logo = iTextSharp.text.Image.GetInstance(iter.Current.GetAttribute("url", ""));
iter = nav.Select("//dokument/gem_som");
iter.MoveNext();
string outputPath = iter.Current.GetAttribute("url", "")+center+".pdf";
iter = nav.Select("//dokument/titel");
iter.MoveNext();
this.titel = center;
Document document = new Document(PageSize.A4, 30, 30, 100, 30);
var outputStream = new FileStream(outputPath, FileMode.Create);
var pdfWriter = PdfWriter.GetInstance(document, outputStream);
pdfWriter.SetLinearPageMode();
var pageEventHandler = new PageEventHandler();
pageEventHandler.ImageHeader = logo;
pdfWriter.PageEvent = pageEventHandler;
DateTime timeOfReport = DateTime.Now.AddMonths(-1);
pageWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
pageHight = document.PageSize.Height - (document.TopMargin + document.BottomMargin);
document.Open();
var title = new Paragraph(titel, titleFont);
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
List<TableOfContentsEntry> _contentsTable = new List<TableOfContentsEntry>();
nav.MoveToRoot();
iter = nav.Select("//dokument/indhold/*");
Chapter chapter = null;
int chapterCount = 1;
while (iter.MoveNext())
{
_contentsTable.Add(new TableOfContentsEntry("Test", pdfWriter.CurrentPageNumber.ToString()));
XPathNodeIterator innerIter = iter.Current.SelectChildren(XPathNodeType.All);
chapter = new Chapter("test", chapterCount);
while(innerIter.MoveNext())
{
if (innerIter.Current.Name.ToString().ToLower().Equals("billede"))
{
image = images[innerIter.Current.GetAttribute("navn", "")];
image.Alignment = Image.ALIGN_CENTER;
image.ScaleToFit(pageWidth, pageHight);
chapter.Add(image);
}
if (innerIter.Current.Name.ToString().ToLower().Equals("sektion"))
{
string line = "";
var afsnit = new Paragraph();
line += (innerIter.Current.GetAttribute("id", "") + " ");
innerIter.Current.MoveToFirstChild();
line += innerIter.Current.Value;
afsnit.Add(line);
innerIter.Current.MoveToNext();
afsnit.Add(innerIter.Current.Value);
chapter.Add(afsnit);
}
}
chapterCount++;
document.Add(chapter);
}
document = CreateTableOfContents(document, pdfWriter, _contentsTable);
document.Close();
}
I'm then calling the method CreateTableOfContents(), and as such it is doing what it is supposed to do. Here's the code for the method:
public Document CreateTableOfContents(Document _doc, PdfWriter _pdfWriter, List<TableOfContentsEntry> _contentsTable)
{
_doc.NewPage();
_doc.Add(new Paragraph("Table of Contents", FontFactory.GetFont("Arial", 18, Font.BOLD)));
_doc.Add(new Chunk(Environment.NewLine));
PdfPTable _pdfContentsTable = new PdfPTable(2);
foreach (TableOfContentsEntry content in _contentsTable)
{
PdfPCell nameCell = new PdfPCell(_pdfContentsTable);
nameCell.Border = Rectangle.NO_BORDER;
nameCell.Padding = 6f;
nameCell.Phrase = new Phrase(content.Title);
_pdfContentsTable.AddCell(nameCell);
PdfPCell pageCell = new PdfPCell(_pdfContentsTable);
pageCell.Border = Rectangle.NO_BORDER;
pageCell.Padding = 6f;
pageCell.Phrase = new Phrase(content.Page);
_pdfContentsTable.AddCell(pageCell);
}
_doc.Add(_pdfContentsTable);
_doc.Add(new Chunk(Environment.NewLine));
/** Reorder pages so that TOC will will be the second page in the doc
* right after the title page**/
int toc = _pdfWriter.PageNumber - 1;
int total = _pdfWriter.ReorderPages(null);
int[] order = new int[total];
for (int i = 0; i < total; i++)
{
if (i == 0)
{
order[i] = 1;
}
else if (i == 1)
{
order[i] = toc;
}
else
{
order[i] = i;
}
}
_pdfWriter.ReorderPages(order);
return _doc;
}
The problem is however. I want to insert a page break before the table of contents, for the sake of reordering the pages, so that the table of contents is the first page, naturally. But the output of the pdf-file is not right.
Here's a picture of what it looks like:
It seems like the _doc.NewPage() in the CreateTableOfContents() method does not execute correctly. Meaning that the image and the table of contents is still on the same page when the method starts the reordering of pages.
EDIT: To clarify the above, the _doc.NewPage() gets executed, but the blank page is added after the picture and the table of contents.
I've read a couple of places that this could be because one is trying to insert a new page after an already blank page. But this is not the case.
I'll just link to the pdf files aswell, to better illustrate the problem.
The pdf with table of contents: with table of contents
The pdf without table of contents: without table of contents
Thank you in advance for your help :)