Images are not coming after creating word Document through Open XML - c#

I am Creating a word document through the c# with the use of OpenXMl sdk.
I am converting all my html page to word document but while converting i am giving a absolute address for my images and after converting it is coming perfectly in my system but when i am trying to take this document to other system the Images are Not Coming there.
I checked the media Directory all images are there but with different Name.
my document is converted but I am Using this mathod.
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(documentPath, true))
{
XNamespace w =
"http://schemas.openxmlformats.org/wordprocessingml/2006/main";
XNamespace r =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships";
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId);
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
using (StreamWriter stringStream = new StreamWriter(chunkStream))
stringStream.Write(html);
XElement altChunk = new XElement(w + "altChunk",
new XAttribute(r + "id", altChunkId)
);
XDocument mainDocumentXDoc = GetXDocument(myDoc);
mainDocumentXDoc.Root
.Element(w + "body")
.Elements(w + "p")
.Last()
.AddAfterSelf(altChunk);
SaveXDocument(myDoc, mainDocumentXDoc);
}
private static XDocument GetXDocument(WordprocessingDocument myDoc)
{
// Load the main document part into an XDocument
XDocument mainDocumentXDoc;
using (Stream str = myDoc.MainDocumentPart.GetStream())
using (XmlReader xr = XmlReader.Create(str))
mainDocumentXDoc = XDocument.Load(xr);
return mainDocumentXDoc;
}
private static void SaveXDocument(WordprocessingDocument myDoc,
XDocument mainDocumentXDoc)
{
// Serialize the XDocument back into the part
using (Stream str = myDoc.MainDocumentPart.GetStream(
FileMode.Create, FileAccess.Write))
using (XmlWriter xw = XmlWriter.Create(str))
mainDocumentXDoc.Save(xw);
}
and this will generate a afchunk.dat file which is showing in the content and the Absolute path.
Basically i doesn't want to create a file through all coding i just want to convert the .html to .docx file .
so can any one tell me how can i convert without getting error in html.

Is there a reason you aren't embedding the images? Here's a link with sample code to show you how.
http://msdn.microsoft.com/en-us/library/bb497430.aspx

Try to create a DocumentResource (Item->Add new) and associate the images there.
Call the Document
using (Stream imgStream = ip.GetStream())
{
System.Drawing.Bitmap logo = DocumentResources._default;
logo.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
Drawing drawing = BuildImage(imageRelationshipID, "_default.jpg", 200, 30);
And create the method to build image in the header or footer;
private static Drawing BuildImage(string imageRelationshipID, string imageName, int pixelWidth, int pixelHeight)
{
int emuWidth = (int)(pixelWidth * EMU_PER_PIXEL);
int emuHeight = (int)(pixelHeight * EMU_PER_PIXEL);
Drawing drawing = new Drawing();
d.Wordprocessing.Inline inline = new d.Wordprocessing.Inline { DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 };
d.Wordprocessing.Anchor anchor = new d.Wordprocessing.Anchor();
d.Wordprocessing.SimplePosition simplePos = new d.Wordprocessing.SimplePosition { X = 0, Y = 0 };
d.Wordprocessing.Extent extent = new d.Wordprocessing.Extent { Cx = emuWidth, Cy = emuHeight };
d.Wordprocessing.DocProperties docPr = new d.Wordprocessing.DocProperties { Id = 1, Name = imageName };
d.Graphic graphic = new d.Graphic();
d.GraphicData graphicData = new d.GraphicData { Uri = GRAPHIC_DATA_URI };
d.Pictures.Picture pic = new d.Pictures.Picture();
d.Pictures.NonVisualPictureProperties nvPicPr = new d.Pictures.NonVisualPictureProperties();
d.Pictures.NonVisualDrawingProperties cNvPr = new d.Pictures.NonVisualDrawingProperties { Id = 2, Name = imageName };
d.Pictures.NonVisualPictureDrawingProperties cNvPicPr = new d.Pictures.NonVisualPictureDrawingProperties();
d.Pictures.BlipFill blipFill = new d.Pictures.BlipFill();
d.Blip blip = new d.Blip { Embed = imageRelationshipID };
d.Stretch stretch = new d.Stretch();
d.FillRectangle fillRect = new d.FillRectangle();
d.Pictures.ShapeProperties spPr = new d.Pictures.ShapeProperties();
d.Transform2D xfrm = new d.Transform2D();
d.Offset off = new d.Offset { X = 0, Y = 0 };
d.Extents ext = new d.Extents { Cx = emuWidth, Cy = emuHeight };
d.PresetGeometry prstGeom = new d.PresetGeometry { Preset = d.ShapeTypeValues.Rectangle };
d.AdjustValueList avLst = new d.AdjustValueList();
xfrm.Append(off);
xfrm.Append(ext);
prstGeom.Append(avLst);
stretch.Append(fillRect);
spPr.Append(xfrm);
spPr.Append(prstGeom);
blipFill.Append(blip);
blipFill.Append(stretch);
nvPicPr.Append(cNvPr);
nvPicPr.Append(cNvPicPr);
pic.Append(nvPicPr);
pic.Append(blipFill);
pic.Append(spPr);
graphicData.Append(pic);
graphic.Append(graphicData);
inline.Append(extent);
inline.Append(docPr);
inline.Append(graphic);
drawing.Append(inline);
return drawing;
}

Related

How to insert Audio file in Word doc Using OpenXml

I'm trying to insert audio file in Word doc using OpenXml. I've implemented my code but no audio file added after executing my Code. I take help OPEN XML SDK Tool 2.5 also. Code seems okay, but no audio inserted.Below is my tried code:
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Emf);
using (var imageStream = new ExportUtils().GetBinaryDataStream())
{
imagePart.FeedData(imageStream);
}
EmbeddedObjectPart embeddedObjectPart = mainPart.AddEmbeddedObjectPart("application/vnd.openxmlformats-officedocument.oleObject");
thumPath = GetMyFilePath(); //Audio file path
using (var objStream = new FileStream(thumPath, FileMode.Open))
{
embeddedObjectPart.FeedData(objStream);
}
AddAudio(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), mainPart.GetIdOfPart(embeddedObjectPart), posX, posY);
Audio Insertion Code
private static void AddAudio(WordprocessingDocument wordDoc, string imgRelationshipId, string objRelationshipId, int x, int y)
{
string style = string.Format("position: absolute; margin - left:{0}pt; margin - top:{1}pt; width: 75.5pt; height: 49pt; z - index:-251657216; mso - position - horizontal - relative:text; mso - position - vertical - relative:text", x, y);
ow.EmbeddedObject embeddedObject = new ow.EmbeddedObject() { DxaOriginal = "1440", DyaOriginal = "1440", AnchorId = "6359C433" };
V.Shape shape = new V.Shape() { Id = "_x0000_s1026", Style = style };
V.ImageData imageData = new V.ImageData() { Title = "Voice", RelationshipId = imgRelationshipId };
shape.Append(imageData);
Ovml.OleObject oleObject = new Ovml.OleObject() { Type = Ovml.OleValues.Embed, ProgId = "Package", ShapeId = "_x0000_s1026", DrawAspect = Ovml.OleDrawAspectValues.Icon, ObjectId = "_1647627410", Id = objRelationshipId };
embeddedObject.Append(shape);
embeddedObject.Append(oleObject);
wordDoc.MainDocumentPart.Document.Body.AppendChild(new ow.Paragraph(new ow.Run(embeddedObject)));
}
My project: x64

Export DocX file with Footer using DocumentFormat.OpenXml

I want to generate a DocX file with footer from HTML.
Using the following lib: DocumentFormat.OpenXml
I manage to generate the DocX file, BUT without Footer.
The code that I use is the following:
class HtmlToDoc
{
public static byte[] GenerateDocX(string html)
{
MemoryStream ms;
MainDocumentPart mainPart;
Body b;
Document d;
AlternativeFormatImportPart chunk;
AltChunk altChunk;
string altChunkID = "AltChunkId1";
ms = new MemoryStream();
using(var myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
{
mainPart = myDoc.MainDocumentPart;
if (mainPart == null)
{
mainPart = myDoc.AddMainDocumentPart();
b = new Body();
d = new Document(b);
d.Save(mainPart);
}
chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkID);
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
{
using (StreamWriter stringStream = new StreamWriter(chunkStream))
{
stringStream.Write("<html><head></head><body>" + html + "</body></html>");
}
}
altChunk = new AltChunk();
altChunk.Id = altChunkID;
mainPart.Document.Body.InsertAt(altChunk, 0);
AddFooter(myDoc);
mainPart.Document.Save();
}
return ms.ToArray();
}
private static void AddFooter(WordprocessingDocument doc)
{
string newFooterText = "New footer via Open XML Format SDK 2.0 classes";
MainDocumentPart mainDocPart = doc.MainDocumentPart;
FooterPart newFooterPart = mainDocPart.AddNewPart<FooterPart>();
string rId = mainDocPart.GetIdOfPart(newFooterPart);
GeneratePageFooterPart(newFooterText).Save(newFooterPart);
foreach (SectionProperties sectProperties in
mainDocPart.Document.Descendants<SectionProperties>())
{
foreach (FooterReference footerReference in
sectProperties.Descendants<FooterReference>())
sectProperties.RemoveChild(footerReference);
FooterReference newFooterReference =
new FooterReference() { Id = rId, Type = HeaderFooterValues.Default };
sectProperties.Append(newFooterReference);
}
mainDocPart.Document.Save();
}
private static Footer GeneratePageFooterPart(string FooterText)
{
PositionalTab pTab = new PositionalTab()
{
Alignment = AbsolutePositionTabAlignmentValues.Center,
RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
Leader = AbsolutePositionTabLeaderCharValues.None
};
var elment =
new Footer(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Footer" }),
new Run(pTab,
new Text(FooterText))
)
);
return elment;
}
}
I tried some other examples too for generating the footer, but the results were the same: generated but WITHOUT footer.
What could be the problem ?
This is how you can add footer to a docx file:
static void Main(string[] args)
{
using (WordprocessingDocument document =
WordprocessingDocument.Open("Document.docx", true))
{
MainDocumentPart mainDocumentPart = document.MainDocumentPart;
// Delete the existing footer parts
mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts);
// Create a new footer part
FooterPart footerPart = mainDocumentPart.AddNewPart<FooterPart>();
// Get Id of footer part
string footerPartId = mainDocumentPart.GetIdOfPart(footerPart);
GenerateFooterPartContent(footerPart);
// Get SectionProperties and Replace FooterReference with new Id
IEnumerable<SectionProperties> sections =
mainDocumentPart.Document.Body.Elements<SectionProperties>();
foreach (var section in sections)
{
// Delete existing references to headers and footers
section.RemoveAllChildren<FooterReference>();
// Create the new header and footer reference node
section.PrependChild<FooterReference>(
new FooterReference() { Id = footerPartId });
}
}
}
static void GenerateFooterPartContent(FooterPart part)
{
Footer footer1 = new Footer();
Paragraph paragraph1 = new Paragraph();
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;
}

Adding image in word document

When I add an image to a word document then, when I open word it is showing me an XML error. The file cannot be opened because there is a problem with the content.
See error ->
I took reference from the below link.
Adding image to word document using OpenXML
and from Microsoft site
https://learn.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
My Code is as follows: add Open XML to your project reference.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
namespace InsertImageWord
{
class Program
{
static void Main(string[] args)
{
//References
//https://www.e-iceblue.com/Tutorials/Spire.Doc/OpenXML/How-to-Insert-a-picture-into-a-word-processing-document.html
//https://coders-corner.net/2015/04/11/open-xml-add-a-picture/
//https://learn.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
//file name
string folder = #"E:\TestImage";
string fileName = folder + #"\BlankDocument.doc";
string imageFileName = folder + #"\DesertTest.png";
//create file
using (var file = WordprocessingDocument.Create(
fileName, WordprocessingDocumentType.Document))
{
file.AddMainDocumentPart();
//add image part and add image from file
ImagePart imagePart = file.MainDocumentPart.AddImagePart(ImagePartType.Png);
using (FileStream stream = new FileStream(imageFileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
//set content
var text = new Text("Hello Open XML world");
var run = new Run(text);
var paragraph = new Paragraph(run);
var body = new Body(paragraph);
var document = new Document(body);
//add image
Drawing imageElement = GetImageElement(
file.MainDocumentPart.GetIdOfPart(imagePart),
imageFileName,
"my image",
22,
22);
body.AppendChild(new Paragraph(new Run(imageElement)));
//save
file.MainDocumentPart.Document = document;
file.MainDocumentPart.Document.Save();
}
}
private static Drawing GetImageElement(
string imagePartId,
string fileName,
string pictureName,
double width,
double height)
{
double englishMetricUnitsPerInch = 914400;
double pixelsPerInch = 96;
//calculate size in emu
double emuWidth = width * englishMetricUnitsPerInch / pixelsPerInch;
double emuHeight = height * englishMetricUnitsPerInch / pixelsPerInch;
var element = new Drawing(
new DW.Inline(
new DW.Extent { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight },
new DW.EffectExtent { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties { Id = (UInt32Value)1U, Name = pictureName },
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties { Id = (UInt32Value)0U, Name = fileName },
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }))
{
Embed = imagePartId,
CompressionState = A.BlipCompressionValues.Print
},
new A.Stretch(new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset { X = 0L, Y = 0L },
new A.Extents { Cx = (Int64Value)emuWidth, Cy = (Int64Value)emuHeight }),
new A.PresetGeometry(
new A.AdjustValueList())
{ Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});
return element;
}
}
}
Please help me out of this. Thanks in Advance
your imageparttype has to match the mimetype of your image

Openxml merging docx with images

In short: I would like to insert the content of a docx that contains images and bullets in another docx.
My problem: I used two approaches:
Manual merge
Altchunk
With both of them I got a corrupted word document as result.
If I remove the images from the docx that I would like to insert in another one, the result docx is OK.
My code:
Manual merge (thanks to https://stackoverflow.com/a/48870385/10075827):
private static void ManualMerge(string firstPath, string secondPath, string resultPath)
{
if (!System.IO.Path.GetFileName(firstPath).StartsWith("~$"))
{
File.Copy(firstPath, resultPath, true);
using (WordprocessingDocument result = WordprocessingDocument.Open(resultPath, true))
{
using (WordprocessingDocument secondDoc = WordprocessingDocument.Open(secondPath, false))
{
OpenXmlElement p = result.MainDocumentPart.Document.Body.Descendants<Paragraph>().Last();
foreach (var e in secondDoc.MainDocumentPart.Document.Body.Elements())
{
var clonedElement = e.CloneNode(true);
clonedElement.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().ToList().ForEach(blip =>
{
var newRelation = result.CopyImage(blip.Embed, secondDoc);
blip.Embed = newRelation;
});
clonedElement.Descendants<DocumentFormat.OpenXml.Vml.ImageData>().ToList().ForEach(imageData =>
{
var newRelation = result.CopyImage(imageData.RelationshipId, secondDoc);
imageData.RelationshipId = newRelation;
});
result.MainDocumentPart.Document.Body.Descendants<Paragraph>().Last();
if (clonedElement is Paragraph)
{
p.InsertAfterSelf(clonedElement);
p = clonedElement;
}
}
}
}
}
}
public static string CopyImage(this WordprocessingDocument newDoc, string relId, WordprocessingDocument org)
{
var p = org.MainDocumentPart.GetPartById(relId) as ImagePart;
var newPart = newDoc.MainDocumentPart.AddPart(p);
newPart.FeedData(p.GetStream());
return newDoc.MainDocumentPart.GetIdOfPart(newPart);
}
Altchunk merge (from http://www.karthikscorner.com/sharepoint/use-altchunk-document-assembly/):
private static void AltchunkMerge(string firstPath, string secondPath, string resultPath)
{
WordprocessingDocument mainDocument = null;
MainDocumentPart mainPart = null;
var ms = new MemoryStream();
#region Prepare - consuming application
byte[] bytes = File.ReadAllBytes(firstPath);
ms.Write(bytes, 0, bytes.Length);
mainDocument = WordprocessingDocument.Open(ms, true);
mainPart = mainDocument.MainDocumentPart;
#endregion
#region Document to be imported
FileStream fileStream = new FileStream(secondPath, FileMode.Open);
#endregion
#region Merge
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, "AltChunkId101");
chunk.FeedData(fileStream);
var altChunk = new AltChunk(new AltChunkProperties() { MatchSource = new MatchSource() { Val = new OnOffValue(true) } });
altChunk.Id = "AltChunkId101";
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
mainPart.Document.Save();
#endregion
#region Mark dirty
var listOfFieldChar = mainPart.Document.Body.Descendants<FieldChar>();
foreach (FieldChar current in listOfFieldChar)
{
if (string.Compare(current.FieldCharType, "begin", true) == 0)
{
current.Dirty = new OnOffValue(true);
}
}
#endregion
#region Save Merged Document
mainPart.DocumentSettingsPart.Settings.PrependChild(new UpdateFieldsOnOpen() { Val = new OnOffValue(true) });
mainDocument.Close();
FileStream file = new FileStream(resultPath, FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
#endregion
}
I spent hours searching for a solution and the most common one I found was to use altchunk. So why is it not working in my case?
If you are able to use the Microsoft.Office.Interop.Word namespace, and able to put a bookmark in the file you want to merge into, you can take this approach:
using Microsoft.Office.Interop.Word;
...
// merge by putting second file into bookmark in first file
private static void NewMerge(string firstPath, string secondPath, string resultPath, string firstBookmark)
{
var app = new Application();
var firstDoc = app.Documents.Open(firstPath);
var bookmarkRange = firstDoc.Bookmarks[firstBookmark];
// Collapse the range to the end, as to not overwrite it. Unsure if you need this
bookmarkRange.Collapse(WdCollapseDirection.wdCollapseEnd);
// Insert into the selected range
// use if relative path
bookmarkRange.InsertFile(Environment.CurrentDirectory + secondPath);
// use if absolute path
//bookmarkRange.InsertFile(secondPath);
}
Related:
C#: Insert and indent bullet points at bookmark in word document using Office Interop libraries

How can I add a header and footer to the generated PDF

I'm using Gmanny's Pechkin Pdf library and it's working perfectly. Here's is my code:
private void CreatePdfPechkin(string htmlString, string fileName)
{
//Transform the HTML into PDF
var pechkin = Factory.Create(new GlobalConfig()
.SetMargins(new Margins(100, 50, 100, 100))
.SetDocumentTitle("Test document")
.SetPaperSize(PaperKind.A4)
.SetCopyCount(1)
//.SetPaperOrientation(true)
// .SetOutputFile("F:/Personal/test.pdf")
);
ObjectConfig oc = new ObjectConfig();
oc.Footer.SetLeftText("[page]");
oc.Footer.SetTexts("[page]", "[date]", "[time]");
oc.Header.SetCenterText("TEST HEADER TEST1");
oc.Header.SetHtmlContent("<h1>TEST HEADER V2</h1>");
oc.SetAllowLocalContent(true);
//// create converter
//IPechkin ipechkin = new SynchronizedPechkin(pechkin);
// set it up using fluent notation
var pdf = pechkin.Convert(new ObjectConfig()
.SetLoadImages(true).SetZoomFactor(1.5)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true), htmlString);
//Return the PDF file
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=test.pdf; size={0}", pdf.Length));
Response.BinaryWrite(pdf);
Response.Flush();
Response.End();
// byte[] pdf = new Pechkin.Synchronized.SynchronizedPechkin(
//new Pechkin.GlobalConfig()).Convert(
// new Pechkin.ObjectConfig()
// .SetLoadImages(true)
// .SetPrintBackground(true)
// .SetScreenMediaType(true)
// .SetCreateExternalLinks(true), htmlString);
// using (FileStream file = System.IO.File.Create(#"F:\Pankaj WorkSpace\"+ fileName))
// {
// file.Write(pdf, 0, pdf.Length);
// }
}
But now I want to add header, footer and page Number, can somebody suggest how to do that?
I know it is possible through Object config I tried but its not working..
Headers and footers using the below very basic examples work for me.
Using Pechkin:
GlobalConfig gc = new GlobalConfig();
gc.SetMargins(new Margins(300, 100, 150, 100))
.SetDocumentTitle("Test document")
.SetPaperSize(PaperKind.Letter);
IPechkin pechkin = new SynchronizedPechkin(gc);
ObjectConfig oc = new ObjectConfig();
oc.SetCreateExternalLinks(false);
oc.SetFallbackEncoding(Encoding.ASCII);
oc.SetLoadImages(false);
oc.Footer.SetCenterText("I'm a footer!");
oc.Footer.SetLeftText("[page]");
oc.Header.SetCenterText("I'm a header!");
byte[] result = pechkin.Convert(oc, "<h1>My Website</h1>");
System.IO.File.WriteAllBytes(#"c:\pechkinTest.pdf", result);
I'd recommend you switch to Tuespechkin though. This is an active fork of Pechkin which includes many bugfixes. Unfortunately active development on Pechkin ceased since 2013.
Using Tuespechkin:
var document = new HtmlToPdfDocument
{
GlobalSettings =
{
ProduceOutline = true,
DocumentTitle = "My Website",
PaperSize = PaperKind.A4,
Margins =
{
All = 1.375,
Unit = Unit.Centimeters
}
},
Objects = {
new ObjectSettings
{
HtmlText = "<h1>My Website</h1>",
HeaderSettings = new HeaderSettings{CenterText = "I'm a header!"},
FooterSettings = new FooterSettings{CenterText = "I'm a footer!", LeftText = "[page]"}
}
}
};
IPechkin converter = Factory.Create();
byte[] result = converter.Convert(document);
System.IO.File.WriteAllBytes(#"c:\tuespechkinTest.pdf", result);
Your issue is this. Instead of creating a new second ObjectConfig, you need to pass the OC you created before which includes the header and footer. Just combine them like this:
ObjectConfig oc = new ObjectConfig();
oc.SetLoadImages(true);
oc.SetZoomFactor(1.5);
oc.SetPrintBackground(true);
oc.SetScreenMediaType(true);
oc.SetCreateExternalLinks(true);
oc.Footer.SetLeftText("[page]");
oc.Footer.SetCenterText("I'm a footer!");
oc.Header.SetCenterText("TEST HEADER TEST1");
var result = pechkin.Convert(oc, "<h1>My Website</h1>");
System.IO.File.WriteAllBytes(#"c:\pechkinTest.pdf", result);

Categories