Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm new to c#. I was looking all over the net for tutorials on how to print pdf, but couldn't find one.
Then I thought, is it possible to read it using itextpdf, like mentioned here
Reading PDF content with itextsharp dll in VB.NET or C#
then print it. If so, how?
A very straight forward approach is to use an installed Adobe Reader or any other PDF viewer capable of printing:
Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
{
CreateNoWindow = true,
Verb = "print",
FileName = path //put the correct path here
};
p.Start( );
Another way is to use a third party component, e.g. PDFView4NET
I wrote a little helper method around the adobereader to bulk-print pdf from c#...:
public static bool Print(string file, string printer) {
try {
Process.Start(
Registry.LocalMachine.OpenSubKey(
#"SOFTWARE\Microsoft\Windows\CurrentVersion" +
#"\App Paths\AcroRd32.exe").GetValue("").ToString(),
string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
return true;
} catch { }
return false;
}
One cannot rely on the return-value of the method btw...
Another approach, if you simply wish to print a PDF file programmatically, is to use the LPR command:
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/lpr
LPR is available on newer versions of Windows too (e.g. Vista/7), but you need to enable it in the Optional Windows Components.
For example:
Process.Start("LPR -S printerdnsalias -P raw C:\files\file.pdf");
You can also use the printer IP address instead of the alias.
This assumes that your printer supports PDF Direct Printing otherwise this will only work for PostScript and ASCII files. Also, the printer needs to have a network interface installed and you need to know it's IP address or alias.
Use PDFiumViewer. I searched for a long time till I came up with a similar solution, then I found this clean piece of code that does not rely on sending raw files to the printer (which is bad if they get interpreted as text files..) or using Acrobat or Ghostscript as a helper (both would need to be installed, which is a hassle):
https://stackoverflow.com/a/41751184/586754
PDFiumViewer comes via nuget, the code example above is complete. Pass in null values for using the default printer.
I had the same problem on printing a PDF file. There's a nuget package called Spire.Pdf that's very simple to use. The free version has a limit of 10 pages although, however, in my case it was the best solution once I don't want to depend on Adobe Reader and I don't want to install any other components.
https://www.nuget.org/packages/Spire.PDF/
PdfDocument pdfdocument = new PdfDocument();
pdfdocument.LoadFromFile(pdfPathAndFileName);
pdfdocument.PrinterName = "My Printer";
pdfdocument.PrintDocument.PrinterSettings.Copies = 2;
pdfdocument.PrintDocument.Print();
pdfdocument.Dispose();
You can create the PDF document using PdfSharp. It is an open source .NET library.
When trying to print the document it get worse. I have looked allover for a open source way of doing it. There are some ways do do it using AcroRd32.exe but it all depends on the version, and it cannot be done without acrobat reader staying open.
I finally ended up using VintaSoftImaging.NET SDK. It costs some money but is much cheaper than the alternative and it solves the problem really easy.
var doc = new Vintasoft.Imaging.Print.ImagePrintDocument { DocumentName = #"C:\Test.pdf" };
doc.Print();
That just prints to the default printer without showing. There are several alternatives and options.
The best way to print pdf automatically from C# is using printer's "direct pdf". You just need to copy the pdf file to printer's network sharename. The rest will be taken care by printer itself.
The speed is 10 times faster than any other methods. However, the requirements are the printer model supporting for direct pdf printing and having at least 128 MB Dram which is easy for any modern printer.
I wrote and released a small Nuget Package which can be used to print a PDF file to a printerdriver. It can also print to a XPS file or PDF file. Here is a link to it.
It is possible to use Ghostscript to read PDF files and print them to a named printer.
Looks like the usual suspects like pdfsharp and migradoc are not able to do that (pdfsharp only if you have Acrobat (Reader) installed).
I found here
https://vishalsbsinha.wordpress.com/2014/05/06/how-to-programmatically-c-net-print-a-pdf-file-directly-to-the-printer/
code ready for copy/paste. It uses the default printer and from what I can see it doesn't even use any libraries, directly sending the pdf bytes to the printer. So I assume the printer also needs to support it, on one 10 year old printer I tested this it worked flawlessly.
Most other approaches - without commercial libraries or applications - require you to draw yourself in the printing device context. Doable but will take a while to figure it out and make it work across printers.
The easiest way is to create C# Process and launch external tool to print your PDF file
private static void ExecuteRawFilePrinter() {
Process process = new Process();
process.StartInfo.FileName = "c:\\Program Files (x86)\\RawFilePrinter\\RawFilePrinter.exe";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.Arguments = string.Format("-p \"c:\\Users\\Me\\Desktop\\mypdffile.pdf\" \"gdn02ptr006\"");
process.Start();
process.WaitForExit();
}
Code above launches RawFilePrinter.exe (similar to 2Printer.exe), but with better support. It is not free, but by making donation allow you to use it everywhere and redistribute with your application. Latest version to download: http://bigdotsoftware.pl/rawfileprinter
It depends on what you are trying to print. You need a third party pdf printer application or if you are printing data of your own you can use report viewer in visual studio. It can output reports to excel and pdf -files.
It is also possible to do it with an embedded web browser, note however that since this might be a local file, and also because it is not actually the browser directly and there is no DOM so there is no ready state.
Here is the code for the approach I worked out on a win form web browser control:
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate(#"path\to\file");
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
//Progress Changed fires multiple times, however after the Navigated event it is fired only once,
//and at this point it is ready to print
webBrowser1.ProgressChanged += (o, args) =>
{
webBrowser1.Print();//Note this does not print only brings up the print preview dialog
//Should be on a separate task to ensure the main thread
//can fully initialize the print dialog
Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);//We need to wait before we can send enter
//This assumes that the print preview is still in focus
Action g = () =>
{
SendKeys.SendWait("{ENTER}");
};
this.Invoke(g);
});
};
}
I advice you to try 2Printer command line tool from:
http://www.doc2prn.com/
Command line example to print all PDF files from folder "C:\Input" is below. You can simple call it from your C# code.
2Printer.exe -s "C:\Input*.PDF" -prn "Canon MP610 series Printer"
If you have Adobe Reader installed, then you should be able to just set it as the default printer. And VOILA! You can print to PDF!
printDocument1.PrinterSettings.PrinterName = "Adobe PDF";
printDocument1.Print();
Just as simple as that!!!
Open, import, edit, merge, convert Acrobat PDF documents with a few lines of code using the intuitive API of Ultimate PDF. By using 100% managed code written in C#, the component takes advantage of the numerous built-in features of the .NET Framework to enhance performance. Moreover, the library is CLS compliant, and it does not use any unsafe blocks for minimal permission requirements. The classes are fully documented with detailed example code which helps shorten your learning curve. If your development environment is Visual Studio, enjoy the full integration of the online documentation. Just mark or select a keyword and press F1 in your Visual Studio IDE, and the online documentation is represented instantly. A high-performance and reliable PDF library which lets you add PDF functionality to your .NET applications easily with a few lines of code.
PDF Component for NET
Related
I need to convert an XPS file I create with my application to a PDF file, what is the best way to do so? I prefer this to be done from inside C# using a managed assembly.
Open source is preferred upon third party solutions
You can use the XpsDocument class to read the XPS files, then use a PDF library (such as Report.Net or #PDF) to export it. I used #PDF back in .NET 1.1, but not sure if it can be easily converted to .NET 2.0.
#PDF:
http://sharppdf.sourceforge.net/
Report.NET:
http://report.sourceforge.net/
An open source managed assembly might be hard to find, but you can look at tallcomponents.com for a commercial product that might help, You can have a look at GhostScript.com, its open source and supports both XPS and PDF, although you may have issues redistributing it without a license.
XPS to PDF document conversion using Ghostscript. Please refer below code snippet to convert XPS to PDF
Process process = new Process();
process.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ghostxps-9.54.0-win32", "gxpswin32.exe");
process.StartInfo.Arguments = $"-sDEVICE=pdfwrite -sOutputFile=\"{pdfFilePath}\" -dNOPAUSE \"{xpsFilePath}\"";
process.Start();
process.WaitForExit();
Please refer below links for more details. click here.
Although it is not free, Amyuni PDF Creator .Net supports loading XPS files and saving them as PDF.
Usual disclaimer applies.
I have a "legacy" VB.NET application (winforms) written for .NET 1.1, and re-compiled under 2.0 that produces a report in HTML via a custom XmlTextWriter wrapper that is suited for HTML. The user then would print the report into pdf if they wanted to.
That was 2003, and now technology has changed a bit, especially within the C#/VB.NET world, and customers want to skip the HTML part, and go to PDF directly. What are my options for open source, or low cost PDF libraries that work well with .NET and must support tables with pictures (generated bitmaps from code) and text.
Here is screen shot of the resulting html rendering
Obviously this needs some cleaning up, tidying it and stuff, but I am interested on known which technology to pursue in this project.
This related question might be what I need, or it may be out of date by now. I don't have any data sources that will provide all the information I want displayed. Currently it is collected from various classes within the application in order to be displayed as html.
anybody have direct experience with iTextSharp or SharpPDF ?
Thanks for any advice.
Update 1:
found possible duplicate here.
I have used iTextSharp to produce PDF reports before. Although you have to get used to the library (and it is an extensive library), once you get the hang of it it isn't so bad. I found the book iText In Action to be very helpful. Even though the book is about the original Java library, not the .NET port, most of the methods and classes are named the same so it wasn't really a problem.
My #1 piece of advice when working with iTextSharp is that you'll be writing a lot of the same code, over and over again. (i.e. creating a table cell, setting the fonts, sizes, colors, and borders for that table cell, setting text...). Do yourself a favor and make your own little Utility class that will do all of your gruntwork for you -- otherwise you'll end up with 2000 lines of code that just create a few tables with some special formatting.
In addition, this site has a series of brief articles that I found useful when I was first learning iTextSharp.
Edit:
If you're interested in an XHTML-->PDF converter, I just found this blog post by Darin Dimitriov that shows how to port the open-source Java flying-saucer library to .NET. He makes it look easy!
Interestingly enough, it seems that flying-saucer uses iText under the hood to perform the conversion.
Report.NET is a .NET PDF library specific for report generation supporting the features you asked for. It is smaller than iTextPdf, but perhaps sufficient for your needs:
http://sourceforge.net/projects/report/
(license is LGPL).
You can use this free print driver:
http://www.dopdf.com/
When you print to it, it outputs PDF.
I was researching this topic two months ago and basically you have two ways:
Dlls
open source iTextSharp - well, don't expect too much from it, it can generate PDFs from simple web pages, your table seems quite complicated though some my I don't think you will succeed with it without some tweaking of it's source code
paid options - I've used ABCPdf, works pretty smoothly, not everything is rendered as good as in browser but does it's job, I believe there are way more libraries like this
Command line tools
If you are lucky enough to have full control over server I think it will be your best option
wkhtmltopdf - good user opinions
htmldoc
I had not tried does two though, I used hosting so they were not an option to me
I just wrote a TIP in CodeProject on how to do this without using any external DLL in a couple of lines.
Here's the short code copied:
// ----------------------------------------------------------------------------------------------
// If you run this on Windows 10 (having it's default printer "Microsoft Print to PDF" installed)
// This should print a PDF file named "CreatedByCSharp.PDF" in your "MyDocuments" folder
// containing the string "When nothing goes right, go left"
// ----------------------------------------------------------------------------------------------
// If not present, you will need to add a reference to System.Drawing in your project References
using System.Drawing;
using System.Drawing.Printing;
void PrintPDF()
{
// Set the output dir and file name
string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = "CreatedByCSharp.pdf";
PrintDocument pDoc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
PrinterName = "Microsoft Print to PDF",
PrintToFile = true,
PrintFileName = System.IO.Path.Combine(directory, file),
}
};
pDoc.PrintPage += new PrintPageEventHandler(Print_Page);
pDoc.Print();
}
void Print_Page(object sender, PrintPageEventArgs e)
{
// Here you can play with the font style (and much much more, this is just an ultra-basic example)
Font fnt = new Font("Courier New", 12);
// Insert the desired text into the PDF file
e.Graphics.DrawString("When nothing goes right, go left", fnt, System.Drawing.Brushes.Black, 0, 0);
}
I ended up using iTextSharp to produce image flashcards with some tricky formatting after becoming deeply frustrated with other libraries.
Where it really paid off was the competent documentation compared to the other options. I believe there is also an option to automatically parse HTML/XML.
I'd also suggest to take a look at PD4ML html to pdf converting library. It has quite a modest price for paid product, but it supports lots of features and is instantly updated.
I'm just creating a simple calculator in C# (windows form)
I've created a "User Help" which is a pdf file, what I want is to display that pdf file if the user clicks on the "Help" button in the WinForm. If assumed that Adobe reader is pre-installed on the user's machine....
How to open the pdf file on button click in winForm?
I don't plan to provide this pdf file on hard disk of user. Which means that I have to embed this pdf into the calculator (winForm) and have to display it on the button click.
Kindly guide me with the best practise for displaying an embedded file in winForm.
You can reference the Adobe Reader ActiveX control and bundle it with your application.
Simply add AcroPDF.PDF.1 to your Toolbox from the COM Components tab (right click toolbox and click Choose Items...) then drag an instance onto your Winform to have the designer create the code for you. Alternately, after adding the necessary reference you can use the following code:
AxAcroPDFLib.AxAcroPDF pdf = new AxAcroPDFLib.AxAcroPDF();
pdf.Dock = System.Windows.Forms.DockStyle.Fill;
pdf.Enabled = true;
pdf.Location = new System.Drawing.Point(0, 0);
pdf.Name = "pdfReader";
pdf.OcxState = ((System.Windows.Forms.AxHost.State)(new System.ComponentModel.ComponentResourceManager(typeof(ViewerWindow)).GetObject("pdfReader.OcxState")));
pdf.TabIndex = 1;
// Add pdf viewer to current form
this.Controls.Add(pdf);
pdf.LoadFile(#"C:\MyPDF.pdf");
pdf.setView("Fit");
pdf.Visible = true;
You could use the WebBrowser control and let IE load a PDF reader for you if there is one installed on the machine.
However the last time I tried this, I had to write the PDF file to disk first, so I could point the WebBrowser control at it.
I would put it on within my program folder, add a link within my Start Menu folder to allow a direct access (without starting my tool) and just at on some click event System.Diagnostics.Process.Start(#".\Manual.pdf");
Update
Ok, now we come to a completely new question: How to embed a file in my application and start it?
For this question you'll find already several answers here, but here is the short version:
Right click your project and select Add - Existing Item
Select your file (don't double click it)
Click the little arrow next to the Add button and select Add As Link
Double click on Properties - Resources.resx
Click the little arrow next to Add Resource and select Add Existing File
Select the same file again in the open dialog
Now you can access the file within your code as byte[] from Properties.Resources.NameOfResource
With these steps you reference your file where ever it exists within your structure. If you like that a copy of your pdf file will be put into a subfolder Resources within your project, just skip the points one and two in the above list.
To get your pdf now opened, you'll have to write the byte[] down to disk (maybe with Path.GetTempFileName()) and start it with Adobe Reader. (Don't forget to delete the file after usage)
There is a C# pdf viewer project on google code. http://code.google.com/p/pdfviewer-win32/
there is the viewer and there is the library that it uses available that uses mupdf and xpdf to render the pdf documents in your winforms program. I am currently developing a User control library for people to use and drop into their programs for pdf viewing capabilities. it works pretty good.
If you want to display a pdf inside your application, the WebBrowser control is probably preferable over the Adobe Reader control, as it will open the file very smoothly in PDF Reader or whatever IE is using as a default to open pdfs. You simply add the WebBrowser control to an existing or new form and navigate to the pdf file.
Never assume that a user has Adobe or any other third party controls or libraries installed on their machines, always package them with your executable or you may have problems.
The Adobe Reader control obviously doesn't integrate as well with .NET as an intrinsic Windows component. As a rule, I always favor the use of built in .Net controls over third party vendors. As far as embedding the file in the actual executable; not going to happen until Microsoft decides any old PDF can be worked into the CLS and compiled into MSIL. What you have when you develop any app in .NET is code that can be compiled into intermediate MSIL to be translated at runtime by the CLR into native code and executed in the OS.
WebBrowser1.Navigate("SomePDF.pdf");
If your user has Adobe Reader (or any other PDF reader) installed on their machine, you could use:
System.Diagnostics.Process.Start(
"My-PDF-file.pdf");
Hope this helps.
Note: Obviously, this will fail if the user does not have any PDF Reader applications installed.
I would suggest converting your pdf file to a Microsoft help file, so that you don't need to have Adobe Reader installed (it's buggy, and has way too much security issues). You cannot expect users to have this.
In reply to the starter's comment:
Yes you would need to create your help file as an HTML document instead of a pdf. There is no easy way to convert pdf to HTML.
Getting the embedded file out should not be a problem at all. This is not dependent on it being .pdf format, and you can just look for a separate solution there.
For display, unless you know Acrobat or similar is installed (well, even Edge can open those files nowadays), or if you want to display the file embedded in a WinForms application, there is
Codeproject Solution
https://www.codeproject.com/Articles/37458/PDF-Viewer-Control-Without-Acrobat-Reader-Installe
written in VB relying on lots of (partially commercial, if your solution is commercial) libraries.
PdfiumViewer
https://github.com/pvginkel/PdfiumViewer
is great and also available via NuGet.
The PdfiumViewer library primarily consists out of three components:
•The PdfViewer control. This control provides a host for the PdfRenderer control and has a default toolbar with limited functionality;
•The PdfRenderer control. This control implements the raw PDF renderer. This control displays a PDF document, provides zooming and scrolling functionality and exposes methods to perform more advanced actions;
•The PdfDocument class provides access to the PDF document and wraps the Pdfium library.
It is an all-in-one solution for display and comes with a friendlier Apache 2.0 license.
edit, added sample code, for your convenience :) I included the following
data = File.ReadAllBytes(#"C:\temp\abc.pdf");
PdfiumViewer.PdfDocument doc;
using (Stream stream = new MemoryStream(data))
{
doc = PdfiumViewer.PdfDocument.Load(stream);
var viewer = new PdfiumViewer.PdfViewer();
viewer.Document = doc;
var form = new System.Windows.Forms.Form();
form.Size = new Size(600, 800);
viewer.Dock = System.Windows.Forms.DockStyle.Fill;
form.Controls.Add(viewer);
form.ShowDialog();
}
This generates a form on the fly, of course you could also use the designer.
It might be possible to embed Adobe's Reader in your form as an ActiveX component. But that means you'll have to make sure Reader is installed on the client machine for that to work.
In case it doesn't have to be strictly embedded you can just launch the PDF file and let whatever viewer the user has open it.
How to open PDF file with relative path
In this case the created Application has to run on several PC´s. To reference on a file which is not in the network, but in the Programm Folder itself, use the following code Snippet:
First of all include the following Library:
using System.IO;
Then use a Button, picturebox, or whatever to create a ClickEvent and use the following code snippet:
private void pictureBox2_Click(object sender, EventArgs e)
{
//get current folderpath of the .exe
string ProgramPath = AppDomain.CurrentDomain.BaseDirectory;
//jump back relative to the .exe-Path to the Resources Path
string FileName = string.Format("{0}Resources\\Master_Thesis_Expose.pdf", Path.GetFullPath(Path.Combine(ProgramPath, #"..\..\")));
//Open PDF
System.Diagnostics.Process.Start(#"" + FileName + "");
}
|Thumb up|
AxAcroPDF1.LoadFile("C:ShippingForm.pdf")
AxAcroPDF1.src = "C:ShippingForm.pdf"
AxAcroPDF1.setShowToolbar(False)
AxAcroPDF1.setView("fitH")
AxAcroPDF1.setLayoutMode("SinglePage")
AxAcroPDF1.setShowScrollbars(False)
AxAcroPDF1.Show()
Does anyone know if the following is possible and if so what the best way of doing it is for free?
I am generating a PrintDocument in a project I am currently working on and displaying a print dialog box so a user can choose which printer they want to use etc. The is currently a windows form application and if a user wants to print to a PDF they can select to print to CutePDF or something similar.
However I am now putting a ASP.Net web frontend on the application and want to use the same code to generate the PrintDocument but want to print it to a PDF on the fly and serve it up via the Response stream in the format of a PDF download.
So my question is....How can I use the current PrintDocument and generate a PDF in memory from it??
Thanks
The System.Drawing code for a PrintDocument can be reused to generate a PDF document with ABCpdf .NET. See the System.Drawing example...
You would have to use a 3rd party component in order to generate the PDF. The following article has some links to some such components: Generating PDF Files from .Net
You're in a world of hurt if you think you're going to run the "same code" that deals with printers in both a forms app and an ASP.NET app.
You might be in luck, however, as it appears that PDFsharp + MigraDoc might be able to do this for you.
I think you will find there is not any tools that will take a PrintDocument as input and render a PDF as output. The only way to do what you want is to "print" the PrintDocument to a "PDF printer driver" that will generate PDF. Basically a virtual printer that will generate PDF instead of printing the actual output. There are a plethora of products on the market for that. A couple that are cheap and widely used are as follows:
Ghostscript with RedMon (open source/GPL or commercial licenses available)
Foxit Software's PDF Creator ($29)
You really should be looking at iTextSharp (it is mentioned on the iText.NET page recommended earlier)
http://itextsharp.sourceforge.net/
PrintDocument is meant for Windows Forms applications but is up and coming in SilverLight, see this video... http://silverlight.net/learn/videos/all/printing-api-basics/
If you wish to continue with the PrintDocument and a web application, I think SilverLight 4 (which is beta right now) is the only way to go, or your going to have to have a lite weight windows form application installed locally for the end user that maybe uses web services.
iTextSharp is a great tool for generating PDFs with .NET on the Internet. I highly recommend it; I've used iText with Java...and have been using iTextSharp for the past few years.
There are several ports of iText for .NET (A very popular open-source PDF library for Java).
http://www.ujihara.jp/iTextdotNET/en/
I have PDF documents from a scanner. This PDF contain forms filled out and signed by staff for a days work. I want to place a bar code or standard area for OCR text on every form type so the batch scan can be programatically broken apart into separate PDF document based on form type.
I would like to do this in Microsoft .net 2.0
I can purchase the require Adobe or other namespaces/dll need to accomplish the task if there are no open source namespaces/dll's available.
Not a free or open source option, but you might also look at ABCPdf by webSuperGoo as another alternative to Adobe.
You can research the iTextSharp library, which can split pdf files.
But it isn't very good for reading the actual pdfs. So I have no idea how it would know where to split them.
There are companies that already do this for you.
You can research the kwiktag company.
iTextSharp will help you split, reassemble, and apply barcodes to pdf's in .NET languages. I dont think it can OCR a document, but I havent looked (I used Abby fine Reader engine).
From the title of your question I'm assuming that you just need to break apart PDF files and that they are already OCR'd. There are a few open source .NET PDF libraries out there. I have successfully used PDFSharp in a project of my own.
Here is a quick snippet that shows how to cull out each page from a PDF document using PDFSharp:
string filePath = #"c:\file.pdf";
using (PdfDocument ipdf = PdfReader.Open(filePath, PdfDocumentOpenMode.ReadOnly))
{
int i = 1;
foreach (PdfPage page in ipdf.Pages)
{
using (PdfDocument opdf = new PdfDocument())
{
opdf.Version = ipdf.Version;
opdf.AddPage(page);
opdf.Save("page " + i++ + ".pdf");
}
}
}
Assuming also that you need to access the text in the document for grouping you can use the PdfPage.Contents property.
You can use several, try these free tools:
PDF Toolkit
Multivalent
check out the Tesseract .NET wrapper (v 2.04.0) around the c++ ocr engine by the same name developed by hp in the late 90's, it won awards for its ingenuity