Last active
January 15, 2021 01:31
-
-
Save albertbaldi/7b8d86a20430e101299fe8a4eccf5deb to your computer and use it in GitHub Desktop.
C# PrintDocument sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
PrintDocument pd = new PrintDocument(); | |
pd.DefaultPageSettings.PrinterSettings.PrinterName = "doPDF v7"; | |
pd.DefaultPageSettings.Landscape = false; | |
pd.DefaultPageSettings.PaperSize = new PaperSize("PaperA4", 826, 1169); | |
pd.DefaultPageSettings.Margins = new Margins(15, 15, 15, 15); | |
pd.OriginAtMargins = true; | |
pd.PrintPage += Pd_PrintPage; | |
pd.Print(); | |
} | |
private static void Pd_PrintPage(object sender, PrintPageEventArgs e) | |
{ | |
//calcula a larguda disponível | |
float availableWidth = (float)Math.Floor(((PrintDocument)sender).OriginAtMargins | |
? e.MarginBounds.Width | |
: (e.PageSettings.Landscape | |
? e.PageSettings.PrintableArea.Height | |
: e.PageSettings.PrintableArea.Width)); | |
//calcula a altura disponível | |
float availableHeight = (float)Math.Floor(((PrintDocument)sender).OriginAtMargins | |
? e.MarginBounds.Height | |
: (e.PageSettings.Landscape | |
? e.PageSettings.PrintableArea.Width | |
: e.PageSettings.PrintableArea.Height)); | |
string texto = string.Empty; | |
Font font = new Font("Arial", 10); | |
SizeF sizeF = e.Graphics.MeasureString(texto, font, (int)availableWidth); | |
//desenha um retangulo na página | |
e.Graphics.DrawRectangle(new Pen(Color.Black, .5F), 0, 0, availableWidth - 2, availableHeight - 2); | |
//imprime um texto na página | |
texto = "Mussum Ipsum, cacilds vidis litro abertis. Praesent malesuada urna nisi, quis volutpat erat hendrerit non. Nam vulputate dapibus. Em pé sem cair, deitado sem dormir, sentado sem cochilar e fazendo pose. Mais vale um bebadis conhecidiss, que um alcoolatra anonimis. Todo mundo vê os porris que eu tomo, mas ninguém vê os tombis que eu levo!"; | |
font = new Font("Arial", 10, FontStyle.Italic); | |
sizeF = e.Graphics.MeasureString(texto, font, (int)availableWidth); | |
e.Graphics.DrawString(texto, | |
font, | |
new SolidBrush(Color.Black), | |
new RectangleF(new PointF(0.1F, 0.1F), sizeF) | |
//new StringFormat { Alignment = StringAlignment.Center } | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment