Use External Css to parse XML - itext

OK i am parsing HTML from a string into a PDFCEll.
It works great thanks to some help from here.
Here is how i am doing it.
How do i use an external css file so i can use class's and not STYLE=""
public class XhtmlToListHelper : IElementHandler
{
// Generic list of elements
public List<IElement> elements = new List<IElement>();
// Add the item to the list
public void Add(IWritable w)
{
if (w is WritableElement)
{
elements.AddRange(((WritableElement)w).Elements());
}
}
string html = "<ul class=\"list\"><li>html 1</li><li>html 2</li><li>html 3</li></ul>";
using (TextReader sr = new StringReader(html))
{
XMLWorkerHelper.GetInstance().ParseXHtml(XhtmlHelper, sr);
}
foreach (var element in XhtmlHelper.elements)
{
if (element.IsContent())
{
PDFCell.AddElement(element);
}
}
Now i have got this far, but how to tye it all in evades me. Any help would be much apreacheted.
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(HttpContext.Current.Server.MapPath("~/Templates/css/core.css"), true);

If you poke around the source here and you should see how to implement it. Basically, your three line using block quadruples in size and complexity:
var XhtmlHelper = new XhtmlToListHelper();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(#"c:\test.css", true);
var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new ElementHandlerPipeline(XhtmlHelper, null)));//Here's where we add our IElementHandler
var worker = new XMLWorker(pipeline, true);
var parser = new XMLParser();
parser.AddListener(worker);
using (TextReader sr = new StringReader(html)) {
parser.Parse(sr);
}

Related

itext7 + pdfHtml: how set portrait orientation and fit content on ConvertToPdf

I did a simple html to pdf conversion getting a landscape orientation.
In the pdfHtml release notes I see that the default orientation should be portrait but I got a landscape.
I'm not able to find the option/parameter/setting to do it.
Probably it is in the ConverterProperties object hidden to my eyes :-(
Any suggestion?
Here is my very simple code
public byte[] HtmlToPdf(string html)
{
using (Stream htmlSource = new MemoryStream(Encoding.UTF8.GetBytes(html)))
using (MemoryStream pdfDest = new MemoryStream())
{
ConverterProperties converterProperties = new ConverterProperties();
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties);
return pdfDest.ToArray();
}
}
EDIT after answers (I got the right orientation!):
Now I have to find a way to scale down the content in order to fit the content and have the right margins without cutting the image.
public static byte[] HtmlToPdf(string html)
{
using (Stream htmlSource = new MemoryStream(Encoding.UTF8.GetBytes(html)))
using (MemoryStream pdfDest = new MemoryStream())
{
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(pdfDest));
pdfDocument.SetDefaultPageSize(PageSize.A4.Rotate());
ConverterProperties converterProperties = new ConverterProperties();
HtmlConverter.ConvertToPdf(htmlSource, pdfDocument, converterProperties);
return pdfDest.ToArray();
}
}
HTML result:
PDF result:
I solved changing the library from itext7 to DinkToPdf. I found it very simple to use and enough to my needs.
The MVC controller after changing the library to DinkToPdf
public byte[] PdfCreatorController(IConverter converter)
string html = await reader.ReadToEndAsync();
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 10 },
DocumentTitle = "Report",
Out = string.Empty,
};
var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent = html,
WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
};
var pdf = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings }
};
return = _converter.Convert(pdf);
}
PDF Result

World map not dispalyed in crystal reports

I'm generating a pdf report using crystal report, I would like to use Data Map Tool
In c# code I've a dataset containing geographicals fields and some values to display in the map.
public class CrystalReportViewerPlugIn : ICrystalReportViewer
{
private ReportDocument _reportDocument;
private CrystalReportViewer _crystalReportViewer;
public void Init(string fileName, DataSet dataSet)
{
_reportDocument = new ReportDocument();
_reportDocument.Load(fileName);
_reportDocument.SetDataSource(dataSet);
_crystalReportViewer = new CrystalReportViewer();
_crystalReportViewer.DisplayToolbar = false;
_crystalReportViewer.DisplayGroupTree = false;
_crystalReportViewer.PageToTreeRatio = 4;
_crystalReportViewer.RefreshReport();
_crystalReportViewer.ReportSource = _reportDocument;
}
}
Then I export the result into a strem:
public MemoryStream GetCrystalReportResults(string rptFileName, DataSet ds)
{
var crystalReportViewer = new CrystalReportViewerPlugIn();
crystalReportViewer.PlugIn.Init(rptFileName, ds);
crystalReportViewer.PlugIn.Control.Visible = true;
var oStream = crystalReportViewer.PlugIn.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
var byteArray = new byte[oStream.Length];
oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
return new MemoryStream(byteArray);
}
The stream is exported as pdf:
protected virtual IHttpActionResult FinalizeExport(MemoryStream data, string name)
{
string contentType = "application/octet-stream";
name = name.GetCleanFileName();
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(data);
response.Content.Headers.Remove("content-type");
response.Content.Headers.Add("content-type", contentType);
response.Content.Headers.Remove("x-filename");
response.Content.Headers.Add("x-filename", name);
response.Content.Headers.Add("Content-Disposition", "inline; filename=\"" + name + "\"");
response.Content.Headers.Add("Content-Length", data.Length.ToString());
return ResponseMessage(response);
}
The world map is not displayed, do you have anny idea about this issue ?
Crystal report's map works only in 32 bits environment.

Empty content on the downloaded PDF using itextsharp in WebAPI 2 response

public IHttpActionResult DownloadPDF()
{
var stream = CreatePdf();
return ResponseMessage(new HttpResponseMessage
{
Content = new StreamContent(stream)
{
Headers =
{
ContentType = new MediaTypeHeaderValue("application/pdf"),
ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myfile.pdf"
}
}
},
StatusCode = HttpStatusCode.OK
});
}
Here is the CreatePdf method:
private Stream CreatePdf()
{
using (var document = new Document(PageSize.A4, 50, 50, 25, 25))
{
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
writer.CloseStream = false;
document.Open();
document.Add(new Paragraph("Hello World"));
document.Close();
output.Seek(0, SeekOrigin.Begin);
return output;
}
}
I can able to download the PDF but the context is empty. Here I am using memory stream and I also tried with file stream its downloading in the respective folder but if I tried to open the downloaded file then also the content is empty. Can anyone help me what I'm missing here?
Here is an approach that usually works for me when using Web API
private byte[] CreatePdf() {
var buffer = new byte[0];
//stream to hold output data
var output = new MemoryStream();
//creation of a document-object
using (var document = new Document(PageSize.A4, 50, 50, 25, 25)) {
//create a writer that listens to the document
// and directs a PDF-stream to output stream
var writer = PdfWriter.GetInstance(document, output);
//open the document
document.Open();
// Create a page in the document
document.NewPage();
// Get the top layer to write some text
var pdfContentBytes = writer.DirectContent;
pdfContentBytes.BeginText();
//add content to page
document.Add(new Paragraph("Hello World"));
//done writing text
pdfContentBytes.EndText();
// make sure any data in the buffer is written to the output stream
writer.Flush();
document.Close();
}
buffer = output.GetBuffer();
return buffer;
}
And then in the action
public IHttpActionResult DownloadPDF() {
var buffer = CreatePdf();
return ResponseMessage(new HttpResponseMessage {
Content = new StreamContent(new MemoryStream(buffer)) {
Headers = {
ContentType = new MediaTypeHeaderValue("application/pdf"),
ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = "myfile.pdf"
}
}
},
StatusCode = HttpStatusCode.OK
});
}

RuntimeBinderException: Convert type System.Threading.Tasks.Task<object> to string

I do an example with signalR. But it doesn't function because of one mistake.
The one mistake (can not convert type system.threading.tasks.task< object> to string) is in this line:
return context.Clients.All.RecieveNotification(simple);
It is at the bottom of the code you can see below.
Below you see the method I wrote. There I do a connection with the database and get the content with a command/query.
Then a few checks and also SqlDependency.
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "SELECT eintrag FROM [dbo].[simple_column]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
simple = dt.Rows[0]["eintrag"].ToString();
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(simple);
}
And here I use the function:
var notifications = $.connection.notificationHub;
notifications.client.recieveNotification = function (simple) {
// Add the message to the page.
$('#dbMessage').text(simple);
};
I hope you can help me.
Thanks.

OpenXML 2 SDK - Word document - Create bulleted list programmatically

Using the OpenXML SDK, 2.0 CTP, I am trying to programmatically create a Word document. In my document I have to insert a bulleted list, an some of the elements of the list must be underlined. How can I do this?
Lists in OpenXML are a little confusing.
There is a NumberingDefinitionsPart that describes all of the lists in the document. It contains information on how the lists should appear (bulleted, numbered, etc.) and also assigns and ID to each one.
Then in the MainDocumentPart, for every item in the list you want to create, you add a new paragraph and assign the ID of the list you want to that paragraph.
So to create a bullet list such as:
Hello,
world!
You would first have to create a NumberingDefinitionsPart:
NumberingDefinitionsPart numberingPart =
mainDocumentPart.AddNewPart<NumberingDefinitionsPart>("someUniqueIdHere");
Numbering element =
new Numbering(
new AbstractNum(
new Level(
new NumberingFormat() { Val = NumberFormatValues.Bullet },
new LevelText() { Val = "·" }
) { LevelIndex = 0 }
) { AbstractNumberId = 1 },
new NumberingInstance(
new AbstractNumId() { Val = 1 }
) { NumberID = 1 });
element.Save(numberingPart);
Then you create the MainDocumentPart as you normally would, except in the paragraph properties, assign the numbering ID:
MainDocumentPart mainDocumentPart =
package.AddMainDocumentPart();
Document element =
new Document(
new Body(
new Paragraph(
new ParagraphProperties(
new NumberingProperties(
new NumberingLevelReference() { Val = 0 },
new NumberingId() { Val = 1 })),
new Run(
new RunProperties(),
new Text("Hello, ") { Space = "preserve" })),
new Paragraph(
new ParagraphProperties(
new NumberingProperties(
new NumberingLevelReference() { Val = 0 },
new NumberingId() { Val = 1 })),
new Run(
new RunProperties(),
new Text("world!") { Space = "preserve" }))));
element.Save(mainDocumentPart);
There is a better explanation of the options available in the OpenXML reference guide in Section 2.9.
I wanted something that would allow me to add more than one bullet list to a document. After banging my head against my desk for a while, I managed to combine a bunch of different posts and examine my document with the Open XML SDK 2.0 Productity Tool and figured some stuff out. The document it produces now passes validation for by version 2.0 and 2.5 of the SDK Productivity tool.
Here is the code; hopefully it saves someone some time and aggravation.
Usage:
const string fileToCreate = "C:\\temp\\bulletTest.docx";
if (File.Exists(fileToCreate))
File.Delete(fileToCreate);
var writer = new SimpleDocumentWriter();
List<string> fruitList = new List<string>() { "Apple", "Banana", "Carrot"};
writer.AddBulletList(fruitList);
writer.AddParagraph("This is a spacing paragraph 1.");
List<string> animalList = new List<string>() { "Dog", "Cat", "Bear" };
writer.AddBulletList(animalList);
writer.AddParagraph("This is a spacing paragraph 2.");
List<string> stuffList = new List<string>() { "Ball", "Wallet", "Phone" };
writer.AddBulletList(stuffList);
writer.AddParagraph("Done.");
writer.SaveToFile(fileToCreate);
Using statements:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
Code
public class SimpleDocumentWriter : IDisposable
{
private MemoryStream _ms;
private WordprocessingDocument _wordprocessingDocument;
public SimpleDocumentWriter()
{
_ms = new MemoryStream();
_wordprocessingDocument = WordprocessingDocument.Create(_ms, WordprocessingDocumentType.Document);
var mainDocumentPart = _wordprocessingDocument.AddMainDocumentPart();
Body body = new Body();
mainDocumentPart.Document = new Document(body);
}
public void AddParagraph(string sentence)
{
List<Run> runList = ListOfStringToRunList(new List<string> { sentence});
AddParagraph(runList);
}
public void AddParagraph(List<string> sentences)
{
List<Run> runList = ListOfStringToRunList(sentences);
AddParagraph(runList);
}
public void AddParagraph(List<Run> runList)
{
var para = new Paragraph();
foreach (Run runItem in runList)
{
para.AppendChild(runItem);
}
Body body = _wordprocessingDocument.MainDocumentPart.Document.Body;
body.AppendChild(para);
}
public void AddBulletList(List<string> sentences)
{
var runList = ListOfStringToRunList(sentences);
AddBulletList(runList);
}
public void AddBulletList(List<Run> runList)
{
// Introduce bulleted numbering in case it will be needed at some point
NumberingDefinitionsPart numberingPart = _wordprocessingDocument.MainDocumentPart.NumberingDefinitionsPart;
if (numberingPart == null)
{
numberingPart = _wordprocessingDocument.MainDocumentPart.AddNewPart<NumberingDefinitionsPart>("NumberingDefinitionsPart001");
Numbering element = new Numbering();
element.Save(numberingPart);
}
// Insert an AbstractNum into the numbering part numbering list. The order seems to matter or it will not pass the
// Open XML SDK Productity Tools validation test. AbstractNum comes first and then NumberingInstance and we want to
// insert this AFTER the last AbstractNum and BEFORE the first NumberingInstance or we will get a validation error.
var abstractNumberId = numberingPart.Numbering.Elements<AbstractNum>().Count() + 1;
var abstractLevel = new Level(new NumberingFormat() {Val = NumberFormatValues.Bullet}, new LevelText() {Val = "·"}) {LevelIndex = 0};
var abstractNum1 = new AbstractNum(abstractLevel) {AbstractNumberId = abstractNumberId};
if (abstractNumberId == 1)
{
numberingPart.Numbering.Append(abstractNum1);
}
else
{
AbstractNum lastAbstractNum = numberingPart.Numbering.Elements<AbstractNum>().Last();
numberingPart.Numbering.InsertAfter(abstractNum1, lastAbstractNum);
}
// Insert an NumberingInstance into the numbering part numbering list. The order seems to matter or it will not pass the
// Open XML SDK Productity Tools validation test. AbstractNum comes first and then NumberingInstance and we want to
// insert this AFTER the last NumberingInstance and AFTER all the AbstractNum entries or we will get a validation error.
var numberId = numberingPart.Numbering.Elements<NumberingInstance>().Count() + 1;
NumberingInstance numberingInstance1 = new NumberingInstance() {NumberID = numberId};
AbstractNumId abstractNumId1 = new AbstractNumId() {Val = abstractNumberId};
numberingInstance1.Append(abstractNumId1);
if (numberId == 1)
{
numberingPart.Numbering.Append(numberingInstance1);
}
else
{
var lastNumberingInstance = numberingPart.Numbering.Elements<NumberingInstance>().Last();
numberingPart.Numbering.InsertAfter(numberingInstance1, lastNumberingInstance);
}
Body body = _wordprocessingDocument.MainDocumentPart.Document.Body;
foreach (Run runItem in runList)
{
// Create items for paragraph properties
var numberingProperties = new NumberingProperties(new NumberingLevelReference() {Val = 0}, new NumberingId() {Val = numberId});
var spacingBetweenLines1 = new SpacingBetweenLines() { After = "0" }; // Get rid of space between bullets
var indentation = new Indentation() { Left = "720", Hanging = "360" }; // correct indentation
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
RunFonts runFonts1 = new RunFonts() { Ascii = "Symbol", HighAnsi = "Symbol" };
paragraphMarkRunProperties1.Append(runFonts1);
// create paragraph properties
var paragraphProperties = new ParagraphProperties(numberingProperties, spacingBetweenLines1, indentation, paragraphMarkRunProperties1);
// Create paragraph
var newPara = new Paragraph(paragraphProperties);
// Add run to the paragraph
newPara.AppendChild(runItem);
// Add one bullet item to the body
body.AppendChild(newPara);
}
}
public void Dispose()
{
CloseAndDisposeOfDocument();
if (_ms != null)
{
_ms.Dispose();
_ms = null;
}
}
public MemoryStream SaveToStream()
{
_ms.Position = 0;
return _ms;
}
public void SaveToFile(string fileName)
{
if (_wordprocessingDocument != null)
{
CloseAndDisposeOfDocument();
}
if (_ms == null)
throw new ArgumentException("This object has already been disposed of so you cannot save it!");
using (var fs = File.Create(fileName))
{
_ms.WriteTo(fs);
}
}
private void CloseAndDisposeOfDocument()
{
if (_wordprocessingDocument != null)
{
_wordprocessingDocument.Close();
_wordprocessingDocument.Dispose();
_wordprocessingDocument = null;
}
}
private static List<Run> ListOfStringToRunList(List<string> sentences)
{
var runList = new List<Run>();
foreach (string item in sentences)
{
var newRun = new Run();
newRun.AppendChild(new Text(item));
runList.Add(newRun);
}
return runList;
}
}
Adam's answer above is correct except it is new NumberingInstance( instead of new Num( as noted in a comment.
Additionally, if you have multiple lists, you should have multiple Numbering elements (each with it's own id eg 1, 2, 3 etc -- one for each list in the document. This doesn't seem to be a problem with bullet lists, but numbered lists will continue using the same numbering sequence (as opposed to starting over again at 1) because it will think that it's the same list. The NumberingId has to be referenced in your paragraph like this:
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
NumberingProperties numberingProperties1 = new NumberingProperties();
NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference() { Val = 0 };
NumberingId numberingId1 = new NumberingId(){ Val = 1 }; //Val is 1, 2, 3 etc based on your numberingid in your numbering element
numberingProperties1.Append(numberingLevelReference1);
numberingProperties1.Append(numberingId1);
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(numberingProperties1);
Children of the Level element will have an effect on the type of bullet, and the indentation.
My bullets were too small until I added this to the Level element:
new NumberingSymbolRunProperties(
new RunFonts() { Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" })
Indentation was a problem until I added this element to the Level element as well:
new PreviousParagraphProperties(
new Indentation() { Left = "864", Hanging = "360" })
And if you are like me - creating a document from a template, then you may want to use this code, to handle both situations - when your template does or does not contain any numbering definitions:
// Introduce bulleted numbering in case it will be needed at some point
NumberingDefinitionsPart numberingPart = document.MainDocumentPart.NumberingDefinitionsPart;
if (numberingPart == null)
{
numberingPart = document.MainDocumentPart.AddNewPart<NumberingDefinitionsPart>("NumberingDefinitionsPart001");
}
Not sure if this helps anyone, but here is my snippet for inserting a list of bullets.
Create the word processing document and word document body
WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open($"{tempFolder}{tempFileName}", true);
Body wordDocumentBody = wordprocessingDocument.MainDocumentPart.Document.Body;
Then get the insert index. This is placeholder text inside the word document, so you can insert into the correct place in the word document.
int insertIndex = wordDocumentBody.ToList().IndexOf(wordDocumentBody.Where(p => p.InnerText.Contains("PLACEHOLDER_TEXT")).First());
You can then call this method to insert into the word document in both bullet points for lettering.
public static void InsertBullets(Body wordDocumentBody, int insertIndex, int bulletStyle, List<string> strToAdd)
{
//// Bullet Styles:
// 1 - Standard bullet
// 2 - Numbered
foreach (string item in strToAdd)
{
Paragraph para = wordDocumentBody.InsertAt(new Paragraph(), insertIndex);
ParagraphProperties paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new ParagraphStyleId() { Val = "ListParagraph" });
paragraphProperties.Append(new NumberingProperties(
new NumberingLevelReference() { Val = 0 },
new NumberingId() { Val = bulletStyle }));
para.Append(paragraphProperties);
para.Append(new Run(
new RunProperties(
new RunStyle() { Val = "ListParagraph" },
new NoProof()),
new Text($"{item}")));
insertIndex++;
}
}
You can then remove the placeholder text after with this.
wordDocumentBody.Elements().ElementAt(wordDocumentBody.ToList().IndexOf(wordDocumentBody.Where(p => p.InnerText.Contains("PLACEHOLDER_TEXT")).First())).Remove();