3
I am developing an application, Console Application in Visual Studio 2015, that its function is to print documents.
I can print TXT and DOC without problems using the class PrintDocument
but I can’t print PDF files. Is there any way to print a PDF with the PrintDocument
?
public void Imprimir(string caminhoImpressora)
{
streamToPrint = new StreamReader(@"C:\Users\3013\Desktop\teste.txt");
printFont = new Font("Arial", 10);
var documento = new PrintDocument();
documento.PrinterSettings.PrintFileName = LocalizarImpressora(caminhoImpressora).ToString();
documento.PrintPage += new PrintPageEventHandler(PrintPage);
documento.Print();
}
This is the method that defines the printer path that will be used and creates the Streamreader object of the txt file. And the code below is the event that reads the lines of the file and formats the text:
private void PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
However, when trying to use the same methods to print a pdf, I can even print it, but they are unreadable code, as if it could not read the content of the pdf itself.
What happens when you try to print a PDF? By the way, enter the code you are using. It doesn’t seem to be a problem to print PDF files with the
PrintDocument
– Jéf Bueno
So I use a method that I found on the internet, where it mounts a Streamreader of the file, and kind of it goes reading line by line of the file, format (changes font, position on the screen, etc.) and then print. I’ll put the code down.
– Vinicius Roberto
I put the code in the post.
– Vinicius Roberto