Problems previewing documents in Windows Form Application - c#

I'm trying to create a WPF which can preview documents(word,pdf,png,jpg) located on my HDD. I've tried using printPreviewControl but I cant get it working.
Code:
public Form1()
{
InitializeComponent();
initComponents();
}
public void initComponents()
{
try
{
string fname = "C:\\Users\\Gebruiker\\Desktop\\PDF en DOC\\test.pdf";
streamToPrint = new StreamReader(fname, Encoding.UTF8);
try
{
PrintDocument pd = new PrintDocument();
pd = new PrintDocument();
pd.DocumentName = fname;
//Get responsive width and height.
System.Drawing.Rectangle workingRectangle = Screen.PrimaryScreen.WorkingArea;
int height = workingRectangle.Height / 100 * 85;
int width = workingRectangle.Width / 100 * 75;
//Settings printPreviewControl
printPreviewControl1.ClientSize = new System.Drawing.Size(width, height);
printPreviewControl1.Location = new System.Drawing.Point(0, 0);
printPreviewControl1.Document = pd;
}
finally
{
streamToPrint.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
*It says its generating the preview, but stays empty, watch image below:
If you guys have any other solution, I'm open to try.
Thanks

Related

Silent printing from WPF

I would like to disable this printing dialog:
What should I do to remove this dialog?
var dlg = new PrintDialog();
dlg.PageRangeSelection = PageRangeSelection.AllPages;
dlg.UserPageRangeEnabled = false;
var doc = new FlowDocument();
doc.PageWidth = 275;
doc.FontSize = 18;
doc.TextAlignment = TextAlignment.Center;
doc.Blocks.Add(new Paragraph(new Run("nXXXXXXXXXXXX")));
dlg.PrintDocument(((IDocumentPaginatorSource)doc).DocumentPaginator, "Receipt");
You can use PrintDocument class instead of PrintDialog.See the Microsoft's implementation
try
{
streamToPrint = new StreamReader
("C:\\My Documents\\MyFile.txt");
try
{
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
(this.pd_PrintPage);
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Print Ribbon using PrintDialog

that drives me nuts. I try to silent print a ribbon (1000 mm height, 150 mm width). The content is a Canvas containing a formatted Text.
If I use "Microsoft Print To PDF" it works and looks OK. When i go on and use the OKI Printer from the pdf it is fine!
If I directly try to print using the OKI, I will get a blank ribbon or (if i change some parameters) I get a very small text in the middle of nowhere.
Any ideas? Unfortunatly it is nearly impossible to Debug.
This is the print function:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
PrintDialog prnt = new PrintDialog();
//PrintQueue queue = new LocalPrintServer().GetPrintQueue("Microsoft Print To PDF");
PrintQueue queue = new LocalPrintServer().GetPrintQueue("OKI C3450");
prnt.PrintQueue = queue;
//var f = queue.GetPrintCapabilities();
prnt.PrintTicket = new PrintTicket();
prnt.PrintTicket.PageMediaSize = new PageMediaSize(3779.53, 566.93);
prnt.PrintTicket.PageOrientation = PageOrientation.Landscape;
//if (prnt.ShowDialog() == true)
//{
Size pageSize = new Size(3779.53, 566.93);
var canvasToPrint = this.backgroundCanvasSchleife1;
this.backgroundCanvasSchleife1.Measure(pageSize);
this.backgroundCanvasSchleife1.Background = new SolidColorBrush(Colors.Transparent);
this.backgroundCanvasSchleife1.Children.RemoveRange(0, this.backgroundCanvasSchleife1.Children.Count-1);
this.backgroundCanvasSchleife1.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height));
//if (prnt.ShowDialog() == true)
//{
// try
//{
prnt.PrintVisual(this.backgroundCanvasSchleife1, "Printing Canvas");
//}catch (Exception ex)
//{
// var t = ex;
//}
//}
//}
//this.Close();
}

Convert Tif document to PDF with PdfSharp

I’m using WinForms. In my form I have a picturebox that displays tif image documents. I’m using PdfSharp as one of my references to convert the tif documents to pdf documents. The good news is I can convert one of the tif pages that is currently displayed in the picturebox.
The problem is when I have a tif document that has more than 1 page, I cannot convert them all into on single Pdf file. For example if I have a tif document image that contains 5 pages, I would want to press a button and convert all those 5 tif pages into 5 pdf pages.
For testing here is a tif document with 5 pages.
Link: http://www.filedropper.com/sampletifdocument5pages
My Code:
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
private string srcFile, destFile;
bool success = false;
private void Open_btn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(dlg.FileName);
lbl_SrcFile.Text = dlg.FileName;
}
dlg.Dispose();
}
private void Save_btn_Click(object sender, EventArgs e)
{
SaveImageToPDF();
}
private void SaveImageToPDF()
{
try
{
string source = lbl_SrcFile.Text;
string savedfile = #"C:\image\Temporary.tif";
pictureBox1.Image.Save(savedfile);
source = savedfile;
string destinaton = #"C:\image\new_PDF_TIF_Document.pdf";
PdfDocument doc = new PdfDocument();
var page = new PdfPage();
XImage img = XImage.FromFile(source);
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]); xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
img.Dispose(); //dispose img in order to free the tmp file for deletion (Make sure the PDF file is closed thats being used)
success = true;
MessageBox.Show(" File saved successfully! \n\nLocation: C:\\image\\New PDF Document.pdf", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(destinaton);
File.Delete(savedfile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
[Edit] Added full working code...with paths hard-coded.
try
{
string destinaton = #"C:\Temp\Junk\new_PDF_TIF_Document.pdf";
Image MyImage = Image.FromFile(#"C:\Temp\Junk\Sample tif document 5 pages.tiff");
PdfDocument doc = new PdfDocument();
for (int PageIndex = 0; PageIndex < MyImage.GetFrameCount(FrameDimension.Page); PageIndex++)
{
MyImage.SelectActiveFrame(FrameDimension.Page, PageIndex);
XImage img = XImage.FromGdiPlusImage(MyImage);
var page = new PdfPage();
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0);
}
doc.Save(destinaton);
doc.Close();
MyImage.Dispose();
MessageBox.Show("File saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
It's been a while since I've used PdfSharp, but you should be able to call the GetFrameCount method on your image, which will tell you how many pages it has.
Then you can use the SelectActiveFrame method to choose which page is active.
PDFsharp-gdi
public static void ToPDF() {
try
{
PdfDocument doc = new PdfDocument();
string source = #"D:\TIF\bb.tif";
string destinaton = #"D:\TIF\bb.pdf";
Image img = Image.FromFile(source);
for (int PageIndex = 0; PageIndex < img.GetFrameCount(FrameDimension.Page); PageIndex++)
{
img.SelectActiveFrame(FrameDimension.Page, PageIndex);
XImage xImg = XImage.FromGdiPlusImage(img);
double width = Math.Ceiling((double)(xImg.Width * 72) / 96);
double height = Math.Ceiling((double)(xImg.Height * 72) / 96);
var page = new PdfPage();
if (xImg.Width > xImg.Height)
{
page.Orientation = PdfSharp.PageOrientation.Landscape;
}
else
{
page.Orientation = PdfSharp.PageOrientation.Portrait;
}
page.Width = width;
page.Height = height;
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(xImg, 0, 0, width, height);
}
doc.Save(destinaton);
doc.Close();
img.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}

custom font prints random characters

I have the following code to print something:
class Print
{
public static void print(string titel, string text, short i, Color color) {
PrintDocument doc = new PrintDocument();
doc.PrintController = new StandardPrintController();
doc.PrintPage += delegate(object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(titel, new Font("Microsoft Sans Serif", 20), new SolidBrush(color), new PointF(30, 40));
PrivateFontCollection pfc = new PrivateFontCollection();
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".Barc.ttf");
byte[] fontdata = new byte[fontStream.Length];
fontStream.Read(fontdata, 0, (int)fontStream.Length);
fontStream.Close();
unsafe
{
fixed (byte * pFontData = fontdata)
{
pfc.AddMemoryFont((System.IntPtr)pFontData, fontdata.Length);
}
}
e1.Graphics.DrawString("*" + text + "*", new Font(pfc.Families[0], 20), new SolidBrush(Color.Black), new PointF(30, 120));
};
doc.PrinterSettings.Copies = i;
try
{
fd.BeginInvoke(doc, null, null);
}
catch (Exception ex)
{
MessageBox.Show("error while printing: " + ex.ToString());
}
}
private delegate void FunctionDelegate(PrintDocument doc);
private static FunctionDelegate fd = new FunctionDelegate(doprint);
private static void doprint(PrintDocument doc)
{
doc.Print();
}
}
When I print something from my computer using (for example) Print.print("A1439213616", "A1439213616", 1, Color.Black) it will work correctly, using the barcode font to print the second line.
But when i copied my program onto another pc, it still printed the first line correctly, but the second line printed, in the default font instead of the custom font, #3) , +1*) +. ) . #. (the only pattern I've been able to spot so far is that the * are getting replaced with # everytime) Whats going wrong here? I am using .NET framework 3.5.
update: without changing anything, now 50% of the time it suddenly does print it correctly and 50% of the time its still the same as before.

Printing user control cuts off half an inch on top and left

I've got a custom control that I'm trying to print. I've tried changing the margin's on my window to "indent" my control, but it still cuts off the left and top. I've also tried the following in my print method:
private void bttnPrint_Click(object sender, RoutedEventArgs e)
{
UserControl hddc = HDDC;
var printDlg = new PrintDialog
{PrintTicket = {PageOrientation = PageOrientation.Landscape, PageBorderless = PageBorderless.Unknown}};
//printDlg.PrintTicket.PageMediaSize.PageMediaSizeName = PageMediaSizeName.NorthAmerica11x17;
if (printDlg.ShowDialog() == true)
{
printDlg.PrintVisual(hddc, "HDDC Report");
}
else
{
MessageBox.Show("Print Canceled");
}
}
Still, no joy. I've got the feeling there's a silly setting I'm missing, but I just can't seem to find it. Why is my print cutting off on the top and left?
public void Printing() {
try {
streamToPrint = new StreamReader (filePath);
try {
PrintDocument prd = new PrintDocument();
prd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
prd.PrinterSettings.PrinterName = printer;
// Set the page orientation to landscape.
prd.DefaultPageSettings.Landscape = true;
prd.Print();
}
finally {
streamToPrint.Close() ;
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
Namespace: System.Drawing.Printing
or maybe this link can help u
Page truncate in right side for landscape orientation with trimmargins using PdfSharp

Categories

Resources