Convet Html string to PDF in Dotnet 7 without warnings - c#

I want to convert an html string into a byte[] pdf and send it as a file for download. But all the libraries I see either have dependency issues or won't work and give errors like "System.Drawing.Common is not supported on this platform.".
I'm working on Ubuntu
Dotnet version 7.0.102
Some packages give warning like -
"Package 'PDFsharp 1.32.3057' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8, .NETFramework,Version=v4.8.1' instead of the project target framework 'net7.0'. This package may not be fully compatible with your project."
this stops me from being able to use hot reload feature when using dotnet watch, it asks me to restart the server on every change.

You can use the iTextSharp library for this.
Please refer to the below code snippet for your reference :
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace HTMLToPDFExample
{
class Program
{
static void Main(string[] args)
{
// Your string HTML here
string html = #"<html><body>
<h1>Example HTML to PDF Conversion</h1>
<p>This is an example of how to convert an HTML string to a PDF document.</p>
</body></html>";
string pdfFile = "example.pdf";
using (var ms = new MemoryStream())
{
using (var doc = new Document(PageSize.A4))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
using (var sr = new StringReader(html))
{
var htmlContext = new HTMLWorker(doc);
htmlContext.Parse(sr);
}
doc.Close();
}
}
File.WriteAllBytes(pdfFile, ms.ToArray());
}
}
}
}

Related

itext7 pdfstream not compressed

I am trying to include an xml file into a pdf/a2 using itext7 and c#.
The xml has to be included into pdf names tree.
I was finally able to do it, the xml stream seems to be in the right names tree position.
There is still a problem, the stream has suppose to be compressed but is not, viewing the output pdf in a notepad you see the plain text.
It seems that the itext7 PdfStream is not able to do it, or at least, I am not able to compress it even setting compressionleve=9 - stream.SetCompressionLevel(9) in my code.
Anyone has a clue on how to do it.
Thank you very much.
Mauro
Here is my code:
using iText.Forms;
using iText.Kernel.Pdf;
using iText.Pdfa;
using iText.Layout.Element;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace PdfXml
{
class Program
{
static void Main(string[] args)
{
string pdfIn = "\\xfar\\pdfin.pdf";
string pdfOut = "\\xfar\\pdfoutU.pdf";
string cdaIn = "\\xfar\\cda.xml";
StreamReader Reader = new StreamReader(cdaIn);
var content = new StringBuilder();
string line;
while (Reader.EndOfStream == false)
{
line = Reader.ReadLine();
content.AppendLine(line);
}
byte[] bytes = Encoding.ASCII.GetBytes(content.ToString());
PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdfIn), new PdfWriter(pdfOut));
PdfStream stream = new PdfStream();;
PdfNameTree nameTree1 = pdfDoc.GetCatalog().GetNameTree(new PdfName("XFAResource"));
stream.SetCompressionLevel(9);
stream.SetData(bytes, true);
stream.Put(PdfName.Filter, PdfName.FlateDecode);
nameTree1.AddEntry("dataset", stream);
nameTree1.BuildTree();
nameTree1.SetModified();
Console.WriteLine("ok");
}
pdfDoc.Close();
}
}
}

Azure Function couldnt find document openXML

I am new in Azure Functions and i am try to discover some features of it.
So i created function blob trigger, added references of OpenXML sdk in project.json
"frameworks": {
"net46":{
"dependencies": {
"WindowsAzure.Storage": "7.0.0" ,
"Open-XML-SDK" : "2.7.2",
"DocumentFormat.OpenXml" : "2.8.1"
And in run.csx i added next code
using System;
using System.IO;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
public static void Run (Stream myBlob, string name, TraceWriter log)
{
// *While we upload a blob, function start to execute*
StreamReader reader = new StreamReader(myBlob);
string S = reader.ReadToEnd();
int numberofSlides = CountSlides(S);
log.Info($"Number of slides = {numberofSlides}");
}
// *here, using XML sdk we open our presentation without using Office*
public static int CountSlides(string presentationFile)
{
using (PresentationDocument presentationDocument =PresentationDocument.Open(presentationFile, false))
{
return CountSlides(presentationDocument);
}
}
public static int CountSlides(PresentationDocument presentationDocument)
{
if (presentationDocument == null)
{
throw new ArgumentNullException("presentationDocument");
}
int slidesCount = 0;
PresentationPart presentationPart = presentationDocument.PresentationPart;
if (presentationPart != null)
{
slidesCount = presentationPart.SlideParts.Count();
}
return slidesCount;
}
The problem is while i upload a .pptx , i have error in log
Exception while executing function: Functions.BlobTriggerCSharp1. mscorlib: Exception has been thrown by the target of an invocation. DocumentFormat.OpenXml: Could not find document.
I upload a file .pptx using Microsoft Azure Storage Explorer and I can not understand why i have an error.
You are using the following method:
public static PresentationDocument Open(
string path,
bool isEditable
)
The first parameter it accepts is path but you pass the file contents in there. It tries to find this weird file path and throws exception.
Try using the Stream overload.

C# editing a fillable form

My Task is to add User name to a fillable pdf (on the margin, not field) using C#. I tried to add a Text Annotation using a lot of Third Party dll like iTextSharp, spire.pdf....
However, whenever I add the text on the fillable pdf and save it, the fillable Fields disappear. Does anyone know how to complete this Task? Thanks.
seems to you use broken pdf file because of it is simple task.
I don't know how looks your code for tools you have tried. I use Apitron PDF Kit. Anyway I think it will look similarly for all tools.
Please see the following code:
using System;
using System.Collections.Generic;
using System.IO;
using Apitron.PDF.Kit.FixedLayout;
using Apitron.PDF.Kit.FixedLayout.Content;
using Apitron.PDF.Kit.FixedLayout.PageProperties;
using Apitron.PDF.Kit.Interactive.Annotations;
using Apitron.PDF.Kit.Interactive.Forms;
public void TestAcroForm_TextBlock()
{
using (Stream stream = new FileStream("filename.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (FixedDocument document = new FixedDocument())
{
Page page = document.Pages[0];
TextField textField = new TextField("UserName", "This is user name");
TextFieldView annotation = new TextFieldView(textField, new Boundary(100, 100, 300, 130));
document.AcroForm.Fields.Add(textField);
page.Annotations.Add(annotation);
using (Stream outStream = new FileStream("filename_out.pdf", FileMode.Create, FileAccess.ReadWrite))
{
document.Save(outStream);
}
}
}
}

I want to copy a document from my tfs project to my local storage using c#

I have some documents in my TFS project,I want to create a console application that reads the documents from TFS and copy the file to my local storage, any idea?
Check the code in this article, which works for you:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string teamProjectCollectionUrl = "http://YourTfsUrl:8080/tfs/YourTeamProjectCollection";
string filePath = #"C:\project\myfile.cs";
// Get the version control server
TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamProjectCollectionUrl));
VersionControlServer versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
// Get the latest Item for filePath
Item item = versionControlServer.GetItem(filePath, VersionSpec.Latest);
// Download and display content to console
string fileString = string.Empty;
using (Stream stream = item.DownloadFile())
{
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
// Use StreamReader to read MemoryStream created from byte array
using (StreamReader streamReader = new StreamReader(new MemoryStream(memoryStream.ToArray())))
{
fileString = streamReader.ReadToEnd();
}
}
}
Console.WriteLine(fileString);
Console.ReadLine();
}
}
}
By the way, you can also use tf get command to get or download a specified version of one or more files or folders from TFS to the workspace, which is an easy way.

In what namespace is FileOutputStream found

I'm building a Console application in VS2010 ASP.NET C# using iTextSharp ver 5.5.2. I have all of the DLLs in the iTextSharp distribution referenced and have the following Using statements:
using System;
using System.IO;
using System.Net;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
I'm looking at an iTextSupport.com posting as an example for the application that contains the following code segment:
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("results/loremipsum.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("/html/loremipsum.html"));
document.close();
On the second line, creating an instance of a PDFWriter, appears the instantiation of "new FileOutputStream" which is throwing an error indicating that a Using statement or a Reference is required. Searching for FileOutputStream in the object browser for both my application AND .NET Framework 4 return no results.
Where is the class containing FileOutputStream to be found?
Maybe you've looked at some Java examples, there's no such beast as a FileOutputStream in .NET. In .NET you could use a System.IO.FileStream:
Document document = new Document();
using (var output = File.Create("results/loremipsum.pdf"))
using (var input = File.Open("html/loremipsum.html"))
{
PdfWriter writer = PdfWriter.GetInstance(document, output);
document.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, input);
document.close();
}
Use httpcontext.current.response.writeoutputstream

Categories

Resources