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
Related
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());
}
}
}
}
I have to convert this Html tempelate written in notepad into PDF using itextsharp
<Body>
<h3>Hello</h3><img src="https://i.stack.imgur.com/nMwn1.png">
</Body>
Install a package called iTextSharp through Nuget Package.
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
public class PdfController : Controller
{
[Route("/htmlpdf")]
public FileStreamResult DownloadPDF()
{
string HTMLContent = "Hello <b>World</b>";// Put your html tempelate here
MemoryStream ms = new MemoryStream();
TextReader txtReader = new StringReader(HTMLContent);
// 1: create object of a itextsharp document class
Document doc = new Document(PageSize.A4, 25, 25, 25, 25);
// 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
PdfWriter PdfWriter = PdfWriter.GetInstance(doc, ms);
PdfWriter.CloseStream = false;
// 3: we create a worker parse the document
HTMLWorker htmlWorker = new HTMLWorker(doc);
// 4: we open document and start the worker on the document
doc.Open();
htmlWorker.StartDocument();
// 5: parse the html into the document
htmlWorker.Parse(txtReader);
// 6: close the document and the worker
htmlWorker.EndDocument();
htmlWorker.Close();
doc.Close();
ms.Flush(); //Always catches me out
ms.Position = 0; //Not sure if this is required
return File(ms, "application/pdf", "HelloWorld.pdf");
}
}
Test of result
//You can also use this free "SelectPdf" library for basic use
SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
//SelectPdf.PdfDocument doc = converter.ConvertUrl("https://google.com");
SelectPdf.PdfDocument doc = converter.ConvertHtmlString(HTMLContent.ToString());
doc.Save("test.pdf");
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();
}
}
}
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);
}
}
}
}
My asp.net c# web-application is creating word documents by filling an existing template word document with data. Now I need to add a further existing documents to that document as next page.
For example: My template has two pages. The document I need to append has one page. As result I want to get one word document with 3 pages.
How do I append documents to an existing word document in asp.net/c# with the Microsoft Open XML SDK 2.0?
Use this code to merge two documents
using System.Linq;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace altChunk
{
class Program
{
static void Main(string[] args)
{
string fileName1 = #"c:\Users\Public\Documents\Destination.docx";
string fileName2 = #"c:\Users\Public\Documents\Source.docx";
string testFile = #"c:\Users\Public\Documents\Test.docx";
File.Delete(fileName1);
File.Copy(testFile, fileName1);
using (WordprocessingDocument myDoc =
WordprocessingDocument.Open(fileName1, true))
{
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk =
mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = File.Open(fileName2, FileMode.Open))
chunk.FeedData(fileStream);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainPart.Document
.Body
.InsertAfter(altChunk, mainPart.Document.Body
.Elements<Paragraph>().Last());
mainPart.Document.Save();
}
}
}
}
This works flawlessly and the same code is also available here.
There is another approach that uses Open XML PowerTools