I want to load in a JPEG file and print it with Aspose.Pdf in C# (.net Framework 4.8). The code I currently have is:
public void PrintImage(string fileToPrint, string printerName, string jobName)
{
System.Drawing.Image srcImage = System.Drawing.Image.FromFile(fileToPrint);
int h = srcImage.Height;
int w = srcImage.Width;
var doc = new Document();
var page = doc.Pages.Add();
var image = new Image();
image.File = (fileToPrint);
page.PageInfo.Height = (h);
page.PageInfo.Width = (w);
page.PageInfo.Margin.Bottom = (0);
page.PageInfo.Margin.Top = (0);
page.PageInfo.Margin.Right = (0);
page.PageInfo.Margin.Left = (0);
page.Paragraphs.Add(image);
var viewer = new PdfViewer(doc);
PrintUsingViewer(viewer, printerName, jobName);
}
private static void PrintUsingViewer(PdfViewer viewer, string printerName, string jobName)
{
viewer.AutoResize = true; // Print the file with adjusted size
viewer.AutoRotate = true; // Print the file with adjusted rotation
viewer.PrintPageDialog = false; // Do not produce the page number dialog when printing
var ps = new System.Drawing.Printing.PrinterSettings();
var pgs = new System.Drawing.Printing.PageSettings();
ps.PrinterName = printerName;
viewer.PrinterJobName = jobName;
viewer.PrintDocumentWithSettings(pgs, ps);
viewer.Close();
}
When I save the document instead of printing and look at it, it seems fine (the image is added). However, when trying to print the image it is not printed and the page is just blank..
I would like to print without first saving the document as a PDF and then trying to print that saved PDF. Does anyone see what I am doing wrong?
The solution was adding this line of code
doc.ProcessParagraphs();
right after this line:
page.Paragraphs.Add(image);
So the code now becomes
public void PrintImage(string fileToPrint, string printerName, string jobName)
{
System.Drawing.Image srcImage = System.Drawing.Image.FromFile(fileToPrint);
int h = srcImage.Height;
int w = srcImage.Width;
var doc = new Document();
var page = doc.Pages.Add();
var image = new Image();
image.File = (fileToPrint);
page.PageInfo.Height = (h);
page.PageInfo.Width = (w);
page.PageInfo.Margin.Bottom = (0);
page.PageInfo.Margin.Top = (0);
page.PageInfo.Margin.Right = (0);
page.PageInfo.Margin.Left = (0);
page.Paragraphs.Add(image);
doc.ProcessParagraphs();
var viewer = new PdfViewer(doc);
PrintUsingViewer(viewer, printerName, jobName);
}
private static void PrintUsingViewer(PdfViewer viewer, string printerName, string jobName)
{
viewer.AutoResize = true; // Print the file with adjusted size
viewer.AutoRotate = true; // Print the file with adjusted rotation
viewer.PrintPageDialog = false; // Do not produce the page number dialog when printing
var ps = new System.Drawing.Printing.PrinterSettings();
var pgs = new System.Drawing.Printing.PageSettings();
ps.PrinterName = printerName;
viewer.PrinterJobName = jobName;
viewer.PrintDocumentWithSettings(pgs, ps);
viewer.Close();
}
Now the image is printed correctly!
Related
I am working on a WinForms application. I use the pdf file to reset the password and the values on pdf are stored as key-value pairs(email: xxxx#mail.com, pass: 11111).
What I want to do:
Read the PDF file line by line and fill the appropriate textboxes.
What I Have done:
public bool CreatePDF(string location, string email, string key)
{
if(location != "" && email != "" && key != "")
{
PdfWriter pdfwriter = new PdfWriter(location);
PdfDocument pdf = new PdfDocument(pdfwriter);
Document document = new Document(pdf);
Paragraph fields = new Paragraph("Email: "+email + "\n" + "Secret Key: "+key);
document.Add(fields);
document.Close();
return true;
}
else
{
return false;
}
}
public string ReadPDF(string location)
{
var pdfDocument = new PdfDocument(new PdfReader(location));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
return text;
}
}
Thank you in advance Guys!. Any suggestions on CreatePDF are also welcome.
This is what I came up with,
var pdfDocument = new PdfDocument(new PdfReader("G:\\Encryption_File.pdf"));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
text.Split('\n');
string line = "";
line = text + "&";
string[] newLines = line.Split('&');
textBox1.Text = newLines[0].Split(':')[1].ToString();
textBox2.Text = newLines[0].Split(':')[2].ToString();
I want to print a .docx file silently and being able to choose the tray of the printer.
At first I tried to print the .docx with the Microsoft.Office.Interop.Word but word is opening...
After I converted the .docx file to an image and printed it with ProcessStartInfo but it shows a printing window to the user.
ProcessStartInfo info = new ProcessStartInfo(imageFilePath);
info.Verb = "Print";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(info);
I tried another method it print the image silently BUT the image is blured and not scaled correctly.
PrinterSettings settings = new PrinterSettings();
string defaultPrinter = settings.PrinterName;
FileInfo fileInfo = new FileInfo(imageFilePath);
PrintDocument pd = new PrintDocument();
pd.DocumentName = fileInfo.Name;
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(imageFilePath);
PrintPageEventArgs arguments = args;
System.Drawing.Rectangle m = new System.Drawing.Rectangle()
{
Y = 0,
X = 0,
Location = new System.Drawing.Point(0, 0),
Height = args.MarginBounds.Height,
Size = args.MarginBounds.Size,
Width = args.MarginBounds.Width
};
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height)
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
args.Graphics.DrawImage(i, m);
};
pd.Print();
So is it possible to print a .docx silently and being able to choose the tray of the printer ?
Did anyone face the same issue. Any help in this regard. Thanks in advance.
I did something very similar to this myself but I never looked up the documentation if you could choose the tray. I believe these are set on the print server itself (if you are using one) and would be able to reference those if your application has the access rights.
string PrinterName = #"\\Server\nameOfThePrinter";
ProcessStartInfo printProcessInfo = new ProcessStartInfo()
{
Verb = "PrintTo",
CreateNoWindow = true,
FileName = pdfFileName,
Arguments = "\"" + PrinterName + "\"",
WindowStyle = ProcessWindowStyle.Hidden
};
Process printProcess = new Process();
printProcess.StartInfo = printProcessInfo;
printProcess.Start();
printProcess.WaitForInputIdle();
printProcess.WaitForExit(10000);
if (printProcess.HasExited)
{
}else
{
printProcess.Kill();
}
return true;
Also, you may want to investigate this article here https://www.codeproject.com/Tips/598424/How-to-Silently-Print-PDFs-using-Adobe-Reader-and
Cheers!
I found a solution I couldn't print a .docx silently so I converted it as a .png image before.
Link to convert .docx to .png
Here is the code to print the image :
PrinterSettings settings = new PrinterSettings();
string PrinterName = settings.PrinterName;
//set paper size
PaperSize oPS = new PaperSize
{
RawKind = (int)PaperKind.A4
};
//choose the tray here
PaperSource oPSource = new PaperSource
{
RawKind = (int)PaperSourceKind.Upper
};
PrintDocument printDoc = new PrintDocument
{
PrinterSettings = settings,
};
//set printer name here it's the default printer
printDoc.PrinterSettings.PrinterName = PrinterName;
printDoc.DefaultPageSettings.PaperSize = oPS;
printDoc.DefaultPageSettings.PaperSource = oPSource;
printDoc.PrintPage += new PrintPageEventHandler((sender, args) =>
{
System.Drawing.Image img = System.Drawing.Image.FromFile(imageFilePath);
int printHeight = (int)printDoc.DefaultPageSettings.PrintableArea.Height;
int printWidth = (int)printDoc.DefaultPageSettings.PrintableArea.Width;
int leftMargin = 0;
int rightMargin = 0;
args.Graphics.DrawImage(img, new System.Drawing.Rectangle(leftMargin, rightMargin, printWidth, printHeight));
});
printDoc.Print();
printDoc.Dispose();
I'm writing a C # method that scans a lot of documents, but I need to scan these documents two-sided, ie for each sheet, scan the front and back of the document using the scanner's ADF. But I've tried all the ways I found on the internet and I could not. My code is below:
//user select the scanner
int indexScanner = Convert.ToInt32(Console.ReadLine());
// Connect to the first available scanner
var device = deviceManager.DeviceInfos[indexScanner - 1].Connect();
// Select the scanner
var scannerItem = device.Items[1];
int resolution = 150;
int width_pixel = 1250;
int height_pixel = 1700;
int color_mode = 1;
int adf_mode = 1;
int pages_mode = 1;
device.Properties["3096"].set_Value(pages_mode);
//device.Properties["3088"].set_Value(adf_mode);
scannerItem.Properties["3088"].set_Value(adf_mode);
AdjustScannerSettings(scannerItem, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode);
CommonDialogClass dlg = new CommonDialogClass();
object scanResult = dlg.ShowTransfer(scannerItem, FormatID.wiaFormatJPEG, true);
if (scanResult != null)
{
ImageFile image = (ImageFile)scanResult;
string filename = "scan.jpeg";
if (File.Exists(filename))
File.Delete(filename);
image.SaveFile(filename);
}
scanResult = dlg.ShowTransfer(scannerItem, FormatID.wiaFormatJPEG, true);
if (scanResult != null)
{
ImageFile image = (ImageFile)scanResult;
string filename = "scan1.jpeg";
if (File.Exists(filename))
File.Delete(filename);
image.SaveFile(filename);
}
I am using the free version of Spire.PDF to print a local pdf file but the print is in grayscale even though the pdf file is in color. Here is my code
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(fileName);
doc.ColorSpace = PdfColorSpace.RGB;
PrintDialog dialogPrint = new PrintDialog();
dialogPrint.AllowPrintToFile = true;
dialogPrint.AllowSomePages = true;
dialogPrint.PrinterSettings.MinimumPage = 1;
dialogPrint.PrinterSettings.MaximumPage = doc.Pages.Count;
dialogPrint.PrinterSettings.FromPage = 1;
dialogPrint.PrinterSettings.ToPage = doc.Pages.Count;
if (dialogPrint.ShowDialog() == DialogResult.OK)
{
//Set the pagenumber which you choose as the start page to print
doc.PrintFromPage = dialogPrint.PrinterSettings.FromPage;
//Set the pagenumber which you choose as the final page to print
doc.PrintToPage = dialogPrint.PrinterSettings.ToPage;
//Set the name of the printer which is to print the PDF
doc.PrinterName = dialogPrint.PrinterSettings.PrinterName;
PrintDocument printDoc = doc.PrintDocument;
printDoc.DefaultPageSettings.Color = true;
dialogPrint.Document = printDoc;
printDoc.Print();
}
I have checked dialogPrint.PrinterSettings.SupportsColor returns true
I have a class that build the content for my table of contents and that works, fine and dandy.
Here's the code:
public void Build(string center,IDictionary<string,iTextSharp.text.Image> images)
{
iTextSharp.text.Image image = null;
XPathDocument rapportTekst = new XPathDocument(Application.StartupPath + #"..\..\..\RapportTemplates\RapportTekst.xml");
XPathNavigator nav = rapportTekst.CreateNavigator();
XPathNodeIterator iter;
iter = nav.Select("//dokument/brevhoved");
iter.MoveNext();
var logo = iTextSharp.text.Image.GetInstance(iter.Current.GetAttribute("url", ""));
iter = nav.Select("//dokument/gem_som");
iter.MoveNext();
string outputPath = iter.Current.GetAttribute("url", "")+center+".pdf";
iter = nav.Select("//dokument/titel");
iter.MoveNext();
this.titel = center;
Document document = new Document(PageSize.A4, 30, 30, 100, 30);
var outputStream = new FileStream(outputPath, FileMode.Create);
var pdfWriter = PdfWriter.GetInstance(document, outputStream);
pdfWriter.SetLinearPageMode();
var pageEventHandler = new PageEventHandler();
pageEventHandler.ImageHeader = logo;
pdfWriter.PageEvent = pageEventHandler;
DateTime timeOfReport = DateTime.Now.AddMonths(-1);
pageWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
pageHight = document.PageSize.Height - (document.TopMargin + document.BottomMargin);
document.Open();
var title = new Paragraph(titel, titleFont);
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
List<TableOfContentsEntry> _contentsTable = new List<TableOfContentsEntry>();
nav.MoveToRoot();
iter = nav.Select("//dokument/indhold/*");
Chapter chapter = null;
int chapterCount = 1;
while (iter.MoveNext())
{
_contentsTable.Add(new TableOfContentsEntry("Test", pdfWriter.CurrentPageNumber.ToString()));
XPathNodeIterator innerIter = iter.Current.SelectChildren(XPathNodeType.All);
chapter = new Chapter("test", chapterCount);
while(innerIter.MoveNext())
{
if (innerIter.Current.Name.ToString().ToLower().Equals("billede"))
{
image = images[innerIter.Current.GetAttribute("navn", "")];
image.Alignment = Image.ALIGN_CENTER;
image.ScaleToFit(pageWidth, pageHight);
chapter.Add(image);
}
if (innerIter.Current.Name.ToString().ToLower().Equals("sektion"))
{
string line = "";
var afsnit = new Paragraph();
line += (innerIter.Current.GetAttribute("id", "") + " ");
innerIter.Current.MoveToFirstChild();
line += innerIter.Current.Value;
afsnit.Add(line);
innerIter.Current.MoveToNext();
afsnit.Add(innerIter.Current.Value);
chapter.Add(afsnit);
}
}
chapterCount++;
document.Add(chapter);
}
document = CreateTableOfContents(document, pdfWriter, _contentsTable);
document.Close();
}
I'm then calling the method CreateTableOfContents(), and as such it is doing what it is supposed to do. Here's the code for the method:
public Document CreateTableOfContents(Document _doc, PdfWriter _pdfWriter, List<TableOfContentsEntry> _contentsTable)
{
_doc.NewPage();
_doc.Add(new Paragraph("Table of Contents", FontFactory.GetFont("Arial", 18, Font.BOLD)));
_doc.Add(new Chunk(Environment.NewLine));
PdfPTable _pdfContentsTable = new PdfPTable(2);
foreach (TableOfContentsEntry content in _contentsTable)
{
PdfPCell nameCell = new PdfPCell(_pdfContentsTable);
nameCell.Border = Rectangle.NO_BORDER;
nameCell.Padding = 6f;
nameCell.Phrase = new Phrase(content.Title);
_pdfContentsTable.AddCell(nameCell);
PdfPCell pageCell = new PdfPCell(_pdfContentsTable);
pageCell.Border = Rectangle.NO_BORDER;
pageCell.Padding = 6f;
pageCell.Phrase = new Phrase(content.Page);
_pdfContentsTable.AddCell(pageCell);
}
_doc.Add(_pdfContentsTable);
_doc.Add(new Chunk(Environment.NewLine));
/** Reorder pages so that TOC will will be the second page in the doc
* right after the title page**/
int toc = _pdfWriter.PageNumber - 1;
int total = _pdfWriter.ReorderPages(null);
int[] order = new int[total];
for (int i = 0; i < total; i++)
{
if (i == 0)
{
order[i] = 1;
}
else if (i == 1)
{
order[i] = toc;
}
else
{
order[i] = i;
}
}
_pdfWriter.ReorderPages(order);
return _doc;
}
The problem is however. I want to insert a page break before the table of contents, for the sake of reordering the pages, so that the table of contents is the first page, naturally. But the output of the pdf-file is not right.
Here's a picture of what it looks like:
It seems like the _doc.NewPage() in the CreateTableOfContents() method does not execute correctly. Meaning that the image and the table of contents is still on the same page when the method starts the reordering of pages.
EDIT: To clarify the above, the _doc.NewPage() gets executed, but the blank page is added after the picture and the table of contents.
I've read a couple of places that this could be because one is trying to insert a new page after an already blank page. But this is not the case.
I'll just link to the pdf files aswell, to better illustrate the problem.
The pdf with table of contents: with table of contents
The pdf without table of contents: without table of contents
Thank you in advance for your help :)