C# Print pdf file programmatically? - c#

My printing code given below
void SaveReport(Telerik.Reporting.Report report, string fileName)
{
ReportProcessor reportProcessor = new ReportProcessor();
Telerik.Reporting.InstanceReportSource instanceReportSource = new Telerik.Reporting.InstanceReportSource();
instanceReportSource.ReportDocument = report;
RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, null);
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
}
// initialize PrintDocument object
PrintDocument doc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
// set the printer to 'Microsoft Print to PDF'
PrinterName = "Canon LBP3000",
// tell the object this document will print to file
// PrintToFile = true,
// set the filename to whatever you like (full path)
PrintFileName = fileName,
}
};
doc.DocumentName = "My";
doc.Print();
}
Then I call the function like
SaveReport(new ThermalPrint(), Server.MapPath(#"~\Report\123.pdf"));
The function executes without error but printer not print the pdf file.
The printer printing dialog like
I can't understand the problem.

If you want to print the report, call reportProcessor.PrintReport(typeReportSource, printerSettings) but make sure you provide a valid PrinterSettings instance.

Related

Remove PDF left and right margins/whitespace when converting to .txt file using C#/Spire.PDF NuGet Package

So I am trying to convert a standard A4 PDF file into a .txt file using Spire.Pdf NuGet Package, and whenever I do it there is a lot of whitespace at the start of each line where the margins of the document go I presume. I managed to solve the issue using the TrimStart() method but I want to be able to do remove the margins using Spire.Pdf itself.
I have played around with setting a PdfTextExtractOptions ExtractArea RectangleF but for some reason it cuts the bottom of the text and I lose rows.
My code is:
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"path");
var content = new List<string>();
RectangleF rectangle = new RectangleF(45, 0, 0, 0);
PdfTextExtractOptions options = new() { IsExtractAllText = true, IsShowHiddenText = true, ExtractArea = rectangle };
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor textExtractor = new(page);
//extract text from a specific rectangular area here - defualt A4 margin sizes?
string extractedText = textExtractor.ExtractText(options);
content.Add(extractedText);
}
FileStream fs = new FileStream(#"outputFile.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
string txtBefore = (string.Join("\n", content));
sw.Write(txtBefore);
Thanks in advance
You can try the code below to extract text from PDF, it will not generate extra white spaces at the start of each line in the result .txt file. I already tested it.
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"test.pdf");
PdfTextExtractOptions options = new PdfTextExtractOptions();
options.IsSimpleExtraction = true;
StringBuilder sb = new StringBuilder();
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor extractor = new PdfTextExtractor(page);
sb.AppendLine(extractor.ExtractText(options));
}
File.WriteAllText("Extract.txt", sb.ToString());

Use PDFsharp-wpf to convert txt files to pdf in C#

I am having issues converting my files to pdf. I am completely new to C# (coming from java) and I am trying to build an application that first prints out a log into a text file then converts it to a PDF. If you know a good resource or example please point me in the right direction without judgement. Thank you!
createPDF(myFileString);
void createPDF(string txtFile)
{
string line = null;
System.IO.TextReader readFile = new StreamReader(myFileString);
int yPoint = 0;
PdfDocument pdf = new PdfDocument();
pdf.Info.Title = "TXT to PDF";
PdfPage pdfPage = pdf.AddPage();
XGraphics graph = XGraphics.FromPdfPage(pdfPage);
while (true)
{
line = readFile.ReadLine();
if (line == null)
{
break; // TODO: might not be correct. Was : Exit While
}
else
{
yPoint = yPoint + 40;
}
}
string pdfFilename = "txttopdf.pdf";
pdf.Save(pdfFilename);
readFile.Close();
readFile = null;
Process.Start(pdfFilename);
}

How to convert png to xps?

I tried to convert png to xps. I fallow this answer .
My code:
XpsDocument xpsDocument = new XpsDocument(#"C:\pathRoot\fileName.xps", FileAccess.ReadWrite);
XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
xpsDocumentWriter.Write(#"C:\pathRoot\fileName.png");
Here I got an exception
System.IO.FileFormatException: 'File contains corrupted data.'
I assumed that answer's author by saying "YourImageYouWishToWrite" means a path to png file like 'C:\pathRoot\fileName.png'. Or I am getting it completely wrong.
the easiest way to do this through printing all Images into Microsoft XPS Writer Printer , then you can merge the output individual XPS files , like :
public void MergeXpsDocument(string outputXPS, string[] ListOfXPS)
{
if (File.Exists(outputXPS))
{
File.Delete(outputXPS);
}
XpsDocument[] XpsFiles = new XpsDocument[ListOfXPS.Length];
for (int i = 0; i < ListOfXPS.Length; i++)
{
XpsDocument xpsFile = new XpsDocument(ListOfXPS[i], FileAccess.Read);
XpsFiles[i] = xpsFile;
}
XpsDocument tempPackage = new XpsDocument(outputXPS, FileAccess.ReadWrite);
XpsDocumentWriter xpsDocWriter = XpsDocument.CreateXpsDocumentWriter(tempPackage);
FixedDocumentSequence fixedDocSequence = new FixedDocumentSequence();
foreach (XpsDocument XPSdoc in XpsFiles)
{
FixedDocumentSequence fixedDocSeq = XPSdoc.GetFixedDocumentSequence();
foreach (DocumentReference sourceSequence in fixedDocSeq.References)
{
DocumentReference docRef = new DocumentReference();
docRef.Source = sourceSequence.Source;
(docRef as IUriContext).BaseUri = (sourceSequence as IUriContext).BaseUri;
FixedDocument fd = docRef.GetDocument(true);
docRef.SetDocument(fd);
fixedDocSequence.References.Add(docRef);
}
}
xpsDocWriter.Write(fixedDocSequence);
tempPackage.Close();

saving a file to a specific path

i have the code for saving a gridview as an html file using a savefiledialog. i want to save it to a specific path (without using the savefiledialog)... how can i do that?
here's my code:
SaveFileDialog dialog = new SaveFileDialog();
dialog.DefaultExt = "*.html";
dialog.Filter = "WORD Document (*.html)|*.html";
if (dialog.ShowDialog() == true)
{
RadDocument document = CreateDocument(rgvReportData);
document.LayoutMode = DocumentLayoutMode.Paged;
document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
document.Arrange(new RectangleF(PointF.Empty, document.DesiredSize));
document.SectionDefaultPageMargin = new Telerik.Windows.Documents.Layout.Padding(2, 2, 2, 2);
document.SectionDefaultPageOrientation = PageOrientation.Landscape;
HtmlFormatProvider provider = new HtmlFormatProvider();
using (Stream output = dialog.OpenFile())
{
provider.Export(document, output);
}
}
how can i sve it without using a savefiledialog?
using(StreamWriter output = new StreamWriter("path\to\your\file")) {
provider.Export(document, output);
}
will do the same thing, but to a specific path. You can read more on file access on MSDN.
String fileName = "youfilename.html"; // give the full path if required
RadDocument document = CreateDocument(rgvReportData);
document.LayoutMode = DocumentLayoutMode.Paged;
document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
document.Arrange(new RectangleF(PointF.Empty, document.DesiredSize));
document.SectionDefaultPageMargin = new Telerik.Windows.Documents.Layout.Padding(2, 2, 2, 2);
document.SectionDefaultPageOrientation = PageOrientation.Landscape;
HtmlFormatProvider provider = new HtmlFormatProvider();
Stream output = File.Open(filename, FileMode.Open, FileAccess.ReadWrite);
provider.Export(document, output);
}
using (var output = new FileStream("path", FileMode.Create, FileAccess.Write))
{
provider.Export(document, output);
}
OpenFileDialog displays the specific path that you have choosen.
You could set the path of the SaveFileDialog, is not necessary to show the dialog like dialog.ShowDialog(), you have just to set the path like dialog.Filename = "file name".
And replace it like :
SaveFileDialog dialog = new SavefileDialog();
dialog.FileName = "path"; // like "C:\\someFolder\\someFile.html"
You could try it

WPF to XPS in landscape orientation

i am trying to to generate a XPS Document from a WPF Control. Printing works so far, but i cannot find a way to create the XPS in landscape mode.
My code to create the XPS file, mostly taken from another SO page
public FixedDocument ReturnFixedDoc()
{
FixedDocument fixedDoc = new FixedDocument();
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
var ctrl = new controlToPrint();
//Create first page of document
fixedPage.Children.Add(ctrl);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
//Create any other required pages here
return fixedDoc;
}
public void SaveCurrentDocument()
{
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "MyReport"; // Default file name
dlg.DefaultExt = ".xps"; // Default file extension
dlg.Filter = "XPS Documents (.xps)|*.xps"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
FixedDocument doc = ReturnFixedDoc();
XpsDocument xpsd = new XpsDocument(filename, FileAccess.Write);
System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
xw.Write(doc);
xpsd.Close();
}
}
Any help is appreciated.
Try setting the size of your FixedPage in ReturnFixedDoc:
// hard coded for A4
fixedPage.Width = 11.69 * 96;
fixedPage.Height = 8.27 * 96;
The numbers are in the form (inches) x (dots per inch). 96 is the DPI of WPF. I have used the dimensions of an A4 page.

Categories