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();
}
Related
I am using C# to generate a Window (scrollbar) with a lot of results: Window ResultsWindow = new Window();
At the bottom, there are two buttons, i.e. Cancel and Print. The first one does what it should. Nevertheless, the Print button should somehow convert the Window into a PDF File, or maybe one step inbetween where the user can save it afterwards.
private void Print_click(object sender, RoutedEventArgs e)
{
//add code to print the whole window??
ResultsWindow.Close();
}
Does anyone of you have an idea how this could work?
Best regards
This isn't particularly pretty (or tested) but uses information from this answer.
This creates an XPS file of your window, and converts it to PDF
using System.IO;
using System.IO.Packaging;
using System.Windows;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
namespace WpfApp8
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
/*
* Convert WPF -> XPS -> PDF
*/
MemoryStream lMemoryStream = new MemoryStream();
Package package = Package.Open(lMemoryStream, FileMode.Create);
XpsDocument doc = new XpsDocument(package);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
// This is your window
writer.Write(this);
doc.Close();
package.Close();
// Convert
MemoryStream outStream = new MemoryStream();
PdfSharp.Xps.XpsConverter.Convert(lMemoryStream, outStream, false);
// Write pdf file
FileStream fileStream = new FileStream("C:\\test.pdf", FileMode.Create);
outStream.CopyTo(fileStream);
// Clean up
outStream.Flush();
outStream.Close();
fileStream.Flush();
fileStream.Close();
}
}
}
It uses the PdfSharp nuget package and the kenjiuno.PdfSharp.Xps package to add XPS support to PdfSharp
Asuming you are using WPF, here is how I accomplished something similar:
private void Button_Click(object sender, RoutedEventArgs e)
{
var wasMax = this.WindowState == WindowState.Maximized;
UBlattWindow.WindowState = WindowState.Normal;
var initHeight = UBlattWindow.ActualHeight;
var initWidth = UBlattWindow.ActualWidth;
UBlattWindow.Width = 955;
UBlattWindow.Height = UBlattWindow.Height + (ScrollerContent.ActualHeight - Scroller.ActualHeight) + 20;
Print(printGrid);
UBlattWindow.Height = initHeight;
UBlattWindow.Width = initWidth;
if (wasMax)
{
UBlattWindow.WindowState = WindowState.Maximized;
}
}
private void Print(Visual v)
{
System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement;
if (e == null)
return;
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == true)
{
PageMediaSize pageSize = null;
pageSize = new PageMediaSize(PageMediaSizeName.ISOA4);
pd.PrintTicket.PageMediaSize = pageSize;
//store original scale
Transform originalScale = e.LayoutTransform;
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / e.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
e.ActualHeight);
//Transform the Visual to scale
e.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
System.Windows.Size sz = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
//update the layout of the visual to the printer page size.
e.Measure(sz);
e.Arrange(new System.Windows.Rect(new System.Windows.Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
//now print the visual to printer to fit on the one page.
pd.PrintVisual(v, "My Print");
//apply the original transform.
e.LayoutTransform = originalScale;
}
}
Note that I use the method Print to scale the Window, so it will fit a ISOA4 format. I also set my window to a fixed width and height before the print and reset it afterwards.
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
Presently, I am attempting to print a data plot created using C#/.NET and GDI+ that has millions of data points. When the document goes to the printer, the printer says it successfully printed the document and that it printed 0 pages. The document never does get printed. Here is some of my code:
private void btnPrint_Click(object sender, EventArgs e)
{
if (_config == null)
{
lblStatus.Text = "Error, config is null";
return;
}
_pd = new PrintDocument();
//PaperSize paperSize = new PaperSize("CustomTest", 1000, 100);
//_pd.DefaultPageSettings.PaperSize = paperSize;
_pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
// Add event handler
_pd.PrintPage += new PrintPageEventHandler(PrintPage);
_pd.BeginPrint += new PrintEventHandler(BeginPrinting);
// Construct print dialog
PrintDialog pDialog = new PrintDialog();
pDialog.AllowSomePages = true;
pDialog.ShowHelp = true;
pDialog.Document = _pd;
// Ask the user for input
DialogResult result = pDialog.ShowDialog();
// Print if user desires
if (result == DialogResult.OK)
{
_pd.Print();
}
}
Does anyone have any suggestions? TIA.
It turned out the corporate print spooler was getting in the way. The solution was to bypass the corporate print system and print directly to the printer, by adding the printer by IP address. It was the PCL6 driver that didn't work.
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
What I'm trying to do is create a Windows Journal (.jrn) file from a .txt. This conversion can be done by printing to a virtual "Journal Note Writer" printer. I've been struggling with a few different methods of getting this to work for a while now, so I've decided to try to simplify things (I hope).
What I Currently Have
Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
FileName = fileToOpen, // My .txt file I'd like to convert to a .jrn
CreateNoWindow = true,
Arguments = "-print-dialog -exit-on-print"
};
p.Start();
This opens the file in Notepad, but does not open the print dialog. I'd like for the print dialog to open and ideally to be able to specify some default options in the print dialog.
Another thing I've tried is this (found in another SO question):
Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
{
CreateNoWindow = true,
Verb = "print",
FileName = fileToOpen
};
p.Start( );
The problem with this is that it just automatically prints the file to the default printer (a physical one) without giving me the option to change it.
What I'm Looking For
At this point I'm just looking for any way to print a .txt to "Windows Note Writer." I've tried doing the printing without going through an external application, and had some trouble with that as well. I haven't been able to find any other references to converting to a .jrn file, so I'm open to ANY ideas.
To get Journal Note Writer as printer you would have to add it into the printer preferences -> Add Printer (I wonder whether it could be done programmatically).
Anyways you can always get a print of a plain .txt file as described here at MSDN.
After struggling with this issue for a while, I decided to go back to trying the handle the printing directly through the application without going through Notepad. The issue I was having before when I tried this was that changing the paper size would break the resulting .jrn file (the printout would be blank). It turns out that changing some paper size settings was necessary to print on a non-native paper size.
Below is the final code in case anybody else struggles with this issue. Thanks for everybody's help.
private void btnOpenAsJRN_Click(object sender, EventArgs e) {
string fileToOpen = this.localDownloadPath + "\\" + this.filenameToDownload;
//Create a StreamReader object
reader = new StreamReader(fileToOpen);
//Create a Verdana font with size 10
lucida10Font = new Font("Lucida Console", 10);
//Create a PrintDocument object
PrintDocument pd = new PrintDocument();
PaperSize paperSize = new PaperSize("Custom", 400, 1097);
paperSize.RawKind = (int)PaperKind.Custom;
pd.DefaultPageSettings.PaperSize = paperSize;
pd.DefaultPageSettings.Margins = new Margins(20, 20, 30, 30);
pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["journalNotePrinter"];
pd.DocumentName = this.filenameToDownload;
//Add PrintPage event handler
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
//Call Print Method
try {
pd.Print();
}
finally {
//Close the reader
if (reader != null) {
reader.Close();
}
this.savedJnt = fileToOpen.Replace("txt", "jnt");
System.Threading.Thread.Sleep(1000);
if (File.Exists(this.savedJnt)) {
lblJntSaved.Visible = true;
lblJntSaved.ForeColor = Color.Green;
lblJntSaved.Text = "File successfully located.";
// If the file can be found, show all of the buttons for completing
// the final steps.
lblFinalStep.Visible = true;
btnMoveToSmoketown.Visible = true;
btnEmail.Visible = true;
txbEmailAddress.Visible = true;
}
else {
lblJntSaved.Visible = true;
lblJntSaved.ForeColor = Color.Red;
lblJntSaved.Text = "File could not be located. Please check your .jnt location.";
}
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs) {
//Get the Graphics object
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
//Read margins from PrintPageEventArgs
float leftMargin = ppeArgs.MarginBounds.Left;
float topMargin = ppeArgs.MarginBounds.Top;
string line = null;
//Calculate the lines per page on the basis of the height of the page and the height of the font
linesPerPage = ppeArgs.MarginBounds.Height /
lucida10Font.GetHeight(g);
//Now read lines one by one, using StreamReader
while (count < linesPerPage &&
((line = reader.ReadLine()) != null)) {
//Calculate the starting position
yPos = topMargin + (count *
lucida10Font.GetHeight(g));
//Draw text
g.DrawString(line, lucida10Font, Brushes.Black,
leftMargin, yPos, new StringFormat());
//Move to next line
count++;
}
//If PrintPageEventArgs has more pages to print
if (line != null) {
ppeArgs.HasMorePages = true;
}
else {
ppeArgs.HasMorePages = false;
}
}