We have started a project for printing, however we are completely stuck when it comes to telling the printer what paper size is selected.
Everytime we select the paper size and hit print, the printer preview is showing A4 everytime and not our selected size although if we open the print preferences the correct size is selected.
namespace CPrint
{
/// <summary>
/// Логика взаимодействия для ucPrint.xaml
/// </summary>
public partial class ucPrint : UserControl
{
bool SystemChange = false;
double? PaperHeight = null;
double? PaperWidth = null;
public ucPrint()
{
InitializeComponent();
App.Localization.AddControls(this, new string[]
{
"cHeader", "lPrinter", "lCopies","lLayout", "bPrintSettings","lColorManagement","lPrinterProfile", "lPositionSize", "cCenter", "lTop", "lLeft"
});
}
public static BitmapSource ConvertColorProfile(BitmapSource bitmapSource, ColorContext sourceProfile, ColorContext destinationProfile)
{
var bitmapConverted = new ColorConvertedBitmap();
bitmapConverted.BeginInit();
bitmapConverted.Source = bitmapSource;
//bitmapConverted.SourceColorContext = new ColorContext(PixelFormats.Pbgra32);// bitmapSourceFrame.ColorContexts == null ? sourceProfile : bitmapSourceFrame.ColorContexts[0];
bitmapConverted.SourceColorContext = sourceProfile;
bitmapConverted.DestinationColorContext = destinationProfile;
bitmapConverted.DestinationFormat = PixelFormats.Bgra32;
bitmapConverted.EndInit();
return bitmapConverted;
}
private void BPrint_Click(object sender, RoutedEventArgs e)
{
if (cPrinter.SelectedItem == null) { MessageBox.Show("Printer not set"); return; }
if (cPaperSize.SelectedItem == null) { MessageBox.Show("Paper size not set"); return; }
double marging = 30;
if (App.CurrentTemplateControl != null)
{
var img = App.CurrentTemplateControl.GetImage(true);
if (img == null) return;
var image = new Image() { Source = img };
if (cColorProfile != null && cColorProfile.SelectedItem != null && cColorProfile.SelectedIndex > 0)
{
Uri sourceProfileUri = new Uri((cColorProfile.SelectedItem as FileInfo).FullName);
image.Source = ConvertColorProfile(image.Source as BitmapSource, new ColorContext(PixelFormats.Pbgra32), new ColorContext(sourceProfileUri));
}
if (cMirror.IsChecked == true)
{
var transformGroup = new TransformGroup();
transformGroup.Children.Add(new ScaleTransform(-1, 1, img.Width / 2, img.Height / 2));
image.RenderTransform = transformGroup;
}
PrintDialog printDialog2 = new PrintDialog();
Size size = (Size)(cPaperSize.SelectedItem as ComboBoxItem).DataContext;
printDialog2.PrintQueue = new PrintQueue(new PrintServer(), cPrinter.Text);
//if (printDialog2.ShowDialog() == true)
//{
//Size size = new Size(printDialog2.PrintableAreaWidth, printDialog2.PrintableAreaHeight);
printDialog2.PrintTicket = new PrintTicket()
{
PageMediaSize = new PageMediaSize(size.Width, size.Height)
};
//printDialog2.PrintTicket
Canvas canvas = new Canvas()
{
//Height = PrintContext.ToPx(size.Height),
//Width = PrintContext.ToPx(size.Width),
Height = size.Height,
Width = size.Width,
Background = Brushes.White
};
canvas.Children.Add(image);
double scaleW = (size.Width - marging * 2) / img.Width;
double scaleH = (size.Height - marging * 2) / img.Height;
if (scaleW < 1 || scaleH < 1)
{
Canvas.SetLeft(image, marging);
Canvas.SetTop(image, marging);
double scale = scaleW > scaleH ? scaleH : scaleW;
var transformGroup = new TransformGroup();
transformGroup.Children.Add(new ScaleTransform(scale, scale, 0, 0));
image.RenderTransform = transformGroup;
}
else if (cCenter.IsChecked == true)
{
Canvas.SetLeft(image, size.Width / 2 - img.Width / 2);
Canvas.SetTop(image, size.Height / 2 - img.Height / 2);
}
else
{
Canvas.SetLeft(image, marging);
Canvas.SetTop(image, marging);
}
printDialog2.PrintVisual(canvas, "Print");
//}
}
return;
}
private void CPrinter_DropDownOpened(object sender, EventArgs e)
{
SystemChange = true;
var lastPrinterName = cPrinter.Text;
cPrinter.Items.Clear();
int index = -1;
cPrinter.SelectedIndex = index;
foreach (string strPrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
index++;
cPrinter.Items.Add(strPrinter);
if (strPrinter == lastPrinterName)
cPrinter.SelectedIndex = index;
}
SystemChange = false;
}
private void CPrinter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0 && SystemChange == false)
{
var printer = new System.Drawing.Printing.PrinterSettings();
printer.PrinterName = e.AddedItems[0].ToString();
var lastPaperName = cPaperSize.Text;
cPaperSize.Items.Clear();
int index = -1;
cPaperSize.SelectedIndex = index;
foreach (System.Drawing.Printing.PaperSize paper in printer.PaperSizes)
{
index++;
cPaperSize.Items.Add(new ComboBoxItem() { Content = paper.PaperName, DataContext = new Size(paper.Width, paper.Height) });
if (paper.PaperName == lastPaperName)
cPaperSize.SelectedIndex = index;
}
Properties.Settings.Default.DefaultDirectPrinter = printer.PrinterName;
Properties.Settings.Default.Save();
}
}
private void CPaperSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
Properties.Settings.Default.DefaultDirectPaper = ((ComboBoxItem)e.AddedItems[0]).Content.ToString();
Properties.Settings.Default.Save();
}
}
public void UpdateControls()
{
SystemChange = true;
if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.DefaultDirectPrinter))
{
SystemChange = true;
var lastPrinterName = cPrinter.Text;
cPrinter.Items.Clear();
int index = -1;
cPrinter.SelectedIndex = index;
foreach (string strPrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
index++;
cPrinter.Items.Add(strPrinter);
if (strPrinter == Properties.Settings.Default.DefaultDirectPrinter)
cPrinter.SelectedIndex = index;
}
SystemChange = false;
if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.DefaultDirectPaper))
{
var printer = new System.Drawing.Printing.PrinterSettings();
printer.PrinterName = Properties.Settings.Default.DefaultDirectPrinter;
string lastPaperName = Properties.Settings.Default.DefaultDirectPaper;
cPaperSize.Items.Clear();
int indexP = -1;
cPaperSize.SelectedIndex = indexP;
foreach (System.Drawing.Printing.PaperSize paper in printer.PaperSizes)
{
indexP++;
cPaperSize.Items.Add(new ComboBoxItem() { Content = paper.PaperName, DataContext = new Size(paper.Width, paper.Height) });
if (paper.PaperName == lastPaperName)
cPaperSize.SelectedIndex = indexP;
}
}
}
if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.DefaultDirectColorProfile))
{
var lastValue = Properties.Settings.Default.DefaultDirectColorProfile;
cColorProfile.Items.Clear();
int index = -1;
cColorProfile.SelectedIndex = index;
cColorProfile.Items.Add("");
index++;
foreach (var file in App.Icc.items)
{
index++;
cColorProfile.Items.Add(file);
if (file.FullName == lastValue)
cColorProfile.SelectedIndex = index;
}
}
SystemChange = false;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
}
private void CColorProfile_DropDownOpened(object sender, EventArgs e)
{
var lastValue = cColorProfile.Text;
cColorProfile.Items.Clear();
int index = -1;
cColorProfile.SelectedIndex = index;
cColorProfile.Items.Add("");
index++;
foreach (var file in App.Icc.items)
{
index++;
cColorProfile.Items.Add(file);
if (file.Name == lastValue)
cColorProfile.SelectedIndex = index;
}
}
private void CColorProfile_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!SystemChange)
{
Properties.Settings.Default.DefaultDirectColorProfile = (cColorProfile.SelectedItem as FileInfo)?.FullName;
Properties.Settings.Default.Save();
}
}
}
}
I expect if we select A5, it tells the print driver to print A5,
If we select a custom "user defined" paper size, it tells the printer which size is selected. And not fixing this at A4 everytime
We cant seem to set the paper size outside the print dialog.
I believe; following this and this MSDN article; you are going to want to do something along the lines of:
System.Drawing.Printing.PaperSize paperSize = new System.Drawing.Printing.PaperSize("custom", width, height);
PrintDocument printDoc = new PrintDocument();
printDoc.DefaultPageSettings.PaperSize = paperSize;
I have walk through your code,
I think some event raise by front end (XAML) on specific use cases that is the overriding the actual value in "Properties.Settings.Default."
It would be better to resolve if you provide a XAML code for this issue.
I can look into it and will give you better solution.
You can share me code here is my skype : shsakariya
Related
I'm Fairly new to WPF and MVVM in general, I'm trying to follow this tutorial to create a stacked bar chart in telerik/WPF C#:
https://docs.telerik.com/devtools/winforms/knowledge-base/chartview-summary-labels-stacked-bars
But I'm, unsure where to implement the "Custom Renderer and Labels" Code, Can't seem to have it work. Should I declare a seperate class or something? A rough step by step guide is all i need, thanks in advance
this is the example code (I'm not sure where to put it)
public class CustomCartesianRenderer : CartesianRenderer
{
public CustomCartesianRenderer(CartesianArea area)
: base(area)
{ }
protected override void InitializeSeriesLabels()
{
base.InitializeSeriesLabels();
IDictionary<object, List<double?>> summaryValues = new Dictionary<object, List<double?>>();
for (int i = 0; i < this.Area.Series.Count; i++)
{
BarSeries barSeries = this.Area.Series[i] as BarSeries;
if (barSeries == null)
{
continue;
}
for (int j = 0; j < barSeries.DataPoints.Count; j++)
{
CategoricalDataPoint dp = (CategoricalDataPoint)barSeries.DataPoints[j];
if (!summaryValues.ContainsKey(dp.Category))
{
summaryValues.Add(dp.Category, new List<double?>() { dp.Value });
}
else
{
summaryValues[dp.Category].Add(dp.Value);
}
}
}
string lastSeriesName = this.Area.Series[this.Area.Series.Count - 1].Name;
for (int i = 0; i < this.DrawParts.Count; i++)
{
BarLabelElementDrawPart labelPart = this.DrawParts[i] as BarLabelElementDrawPart;
if (labelPart != null && labelPart.Element.Name == lastSeriesName)
{
CustomBarLabelElementDrawPart customLabelPart = new CustomBarLabelElementDrawPart((BarSeries)labelPart.Element, this);
customLabelPart.SummaryValues = summaryValues;
this.DrawParts[i] = customLabelPart;
}
}
}
}
public class CustomBarLabelElementDrawPart : BarLabelElementDrawPart
{
private IDictionary<object, List<double?>> summaryValues;
public CustomBarLabelElementDrawPart(BarSeries series, IChartRenderer renderer)
: base(series, renderer)
{ }
public IDictionary<object, List<double?>> SummaryValues
{
get
{
return this.summaryValues;
}
set
{
this.summaryValues = value;
}
}
public override void Draw()
{
Graphics graphics = this.Renderer.Surface as Graphics;
RadGdiGraphics radGraphics = new RadGdiGraphics(graphics);
foreach (DataPointElement dataPointElement in this.Element.Children)
{
CategoricalDataPoint categoricalDataPoint = dataPointElement.DataPoint as CategoricalDataPoint;
if (!this.summaryValues.ContainsKey(categoricalDataPoint.Category))
{
continue;
}
double? sum = this.summaryValues[categoricalDataPoint.Category].Sum();
string summaryText = string.Format("Sum: {0}", sum);
RadRect slot = categoricalDataPoint.LayoutSlot;
RectangleF barBounds = new RectangleF((float)(this.OffsetX + slot.X), (float)(this.OffsetY + slot.Y), (float)slot.Width, (float)slot.Height);
float realHeight = barBounds.Height * dataPointElement.HeightAspectRatio;
barBounds.Y += barBounds.Height - realHeight;
barBounds.Height = realHeight;
barBounds = this.AdjustBarDataPointBounds(dataPointElement, barBounds);
barBounds.Width = Math.Max(barBounds.Width, 1f);
object state = radGraphics.SaveState();
int horizontalTranslate = (int)(barBounds.X + barBounds.Width / 2);
int verticalTranslate = (int)(barBounds.Y + barBounds.Height / 2);
float angle = (float)this.Element.LabelRotationAngle % 360f;
if (angle != 0)
{
radGraphics.TranslateTransform(horizontalTranslate, verticalTranslate);
radGraphics.RotateTransform(angle);
radGraphics.TranslateTransform(-horizontalTranslate, -verticalTranslate);
}
Size desiredSize = TextRenderer.MeasureText(summaryText, dataPointElement.Font);
FillPrimitiveImpl fill = new FillPrimitiveImpl(dataPointElement, null);
fill.PaintFill(radGraphics, 0, Size.Empty, barBounds);
BorderPrimitiveImpl border = new BorderPrimitiveImpl(dataPointElement, null);
border.PaintBorder(radGraphics, 0, Size.Empty, barBounds);
using (Brush brush = new SolidBrush(dataPointElement.ForeColor))
{
RectangleF drawRectangle = new RectangleF();
drawRectangle.X = barBounds.X + dataPointElement.Padding.Left + (barBounds.Width - desiredSize.Width) /2;
drawRectangle.Y = barBounds.Y + dataPointElement.Padding.Top - desiredSize.Height;
drawRectangle.Width = barBounds.Width - dataPointElement.Padding.Right;
drawRectangle.Height = barBounds.Height - dataPointElement.Padding.Bottom;
StringFormat format = new StringFormat();
graphics.DrawString(summaryText, dataPointElement.Font, brush, drawRectangle, format);
}
if (angle != 0)
{
radGraphics.ResetTransform();
}
radGraphics.RestoreState(state);
}
base.Draw();
}
private RectangleF AdjustBarDataPointBounds(DataPointElement point, RectangleF bounds)
{
RectangleF barBounds = bounds;
if (point.BorderBoxStyle == BorderBoxStyle.SingleBorder || point.BorderBoxStyle == BorderBoxStyle.OuterInnerBorders)
{
barBounds.X += point.BorderWidth - (int)((point.BorderWidth - 1f) / 2f);
barBounds.Width -= point.BorderWidth;
barBounds.Y += point.BorderWidth - (int)((point.BorderWidth - 1f) / 2f);
barBounds.Height -= point.BorderWidth;
}
else if (point.BorderBoxStyle == BorderBoxStyle.FourBorders)
{
barBounds.Y += 1;
barBounds.Height -= 1;
barBounds.X += 1;
barBounds.Width -= 1;
}
if (((CartesianRenderer)this.Renderer).Area.Orientation == System.Windows.Forms.Orientation.Horizontal)
{
barBounds.X--;
}
return barBounds;
}
}
I have a form like this. You can see my dynamic groupbox (30 groupbox) in Flowlayout on the right, and a picturebox to show questions on the left.
I'm worndering that How to use Click event for each groupbox to show the question equivalent in Picturebox?
Here's my code of groupbox
public GroupBox gbx(String name, int s, string i, string msch)
{
this.Name = int.Parse(i);
this.sda = s;
this.MsCauHoi = msch;
// gb
//
if (s == 2)
{
gb.Controls.Add(cb1);
gb.Controls.Add(cb2);
}
if (s == 3)
{
gb.Controls.Add(cb1);
gb.Controls.Add(cb2);
gb.Controls.Add(cb3);
}
if (s == 4)
{
gb.Controls.Add(cb1);
gb.Controls.Add(cb2);
gb.Controls.Add(cb3);
gb.Controls.Add(cb4);
}
gb.Location = new System.Drawing.Point(219, 44);
gb.Margin = new System.Windows.Forms.Padding(1, 1, 1, 1);
gb.Name = name;
gb.Padding = new System.Windows.Forms.Padding(1, 1, 1, 1);
gb.Size = new System.Drawing.Size(120, 45);
gb.TabIndex = 7;
gb.TabStop = false;
gb.Text = i;
gb.BackColor = Color.Silver;
//
// cb1
//
cb1.AutoSize = true;
cb1.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb1.Location = new System.Drawing.Point(15, 13);
cb1.Margin = new System.Windows.Forms.Padding(0);
cb1.Name = "cb1";
cb1.Size = new System.Drawing.Size(17, 31);
cb1.TabIndex = 0;
cb1.Text = "1";
cb1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb1.UseVisualStyleBackColor = true;
cb1.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
//
// cb2
//
cb2.AutoSize = true;
cb2.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb2.Location = new System.Drawing.Point(35, 13);
cb2.Name = "cb2";
cb2.Size = new System.Drawing.Size(17, 31);
cb2.TabIndex = 1;
cb2.Text = "2";
cb2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb2.UseVisualStyleBackColor = true;
cb2.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
//
// cb3
//
cb3.AutoSize = true;
cb3.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb3.Location = new System.Drawing.Point(58, 13);
cb3.Name = "cb3";
cb3.Size = new System.Drawing.Size(17, 31);
cb3.TabIndex = 2;
cb3.Text = "3";
cb3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb3.UseVisualStyleBackColor = true;
cb3.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
//
// cb4
//
cb4.AutoSize = true;
cb4.CheckAlign = System.Drawing.ContentAlignment.BottomCenter;
cb4.Location = new System.Drawing.Point(81, 13);
cb4.Name = "cb4";
cb4.Size = new System.Drawing.Size(17, 31);
cb4.TabIndex = 3;
cb4.Text = "4";
cb4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
cb4.UseVisualStyleBackColor = true;
cb4.CheckedChanged += delegate (object sender, EventArgs e)
{
CheckBox b = new CheckBox();
b = (CheckBox)sender;
if (b.Checked == true)
{
gb.BackColor = Color.Turquoise;
}
};
return gb;
}
And here's the code of FormLoad
private void FrmThi_Load(object sender, EventArgs e)
{
droptable();
this.CauDaLam = 0;
if (dethi == null) setdethi();
Screen scr = Screen.PrimaryScreen; //đi lấy màn hình chính
this.Left = (scr.WorkingArea.Width - this.Width) / 2;
this.Top = (scr.WorkingArea.Height - this.Height) / 2;
int i = 0;
foreach (DataRow row in this.dethi.Rows)
{
String myValue = row["SoDA"].ToString();
String msch = row["MaCH"].ToString();
ptl = new FrmPhieuTraLoi();
pn_DeThi.Controls.Add(ptl.gbx("cau" + (i + 1).ToString(), int.Parse(myValue), (i + 1).ToString(), msch));
listptl.Add(ptl);
i++;
}
loadcauhoi(this.CauDangLam);
listptl[CauDangLam].setBackColorCDL();
Random r = new Random();
lbmade1.Text = r.Next(1, 4).ToString();
txt = lbSatHachBangLai.Text;
len = txt.Length;
lbSatHachBangLai.Text = "";
timer1.Start();
this.timer2.Start();
}
This is an example code:
private void Form1_Load(object sender, EventArgs e)
{
for(int idx = 0; idx < 5; idx++)
{
var gBox = new GroupBox();
gBox.Height = 50;
gBox.Width = 50;
gBox.Text = "Box: " + idx;
gBox.Tag = idx;
gBox.MouseClick += GBox_MouseClick;
this.Controls.Add(gBox);
}
}
private void GBox_MouseClick(object sender, MouseEventArgs e)
{
//var ctrl = sender as Control; -- Not required
int questionIdx = (int)(sender as Control).Tag;
}
I would extend the GroupBox control and add a property for the Question ID (Add new Item > Custom Control) and change the class to look like this:
public partial class QuestionGroupBox : GroupBox
{
public string QuestionID;
public QuestionGroupBox()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}
Then populate your flowlayout and set the QuestionID and Click EventHandler, similar to this:
var gb = new QuestionGroupBox{ QuestionID = "44"};
gb.Click += new System.EventHandler(this.questionGroupBox_Click);
//add add to your flow layout
Finally create your event handler to get and display the question
private void questionGroupBox_Click(object sender, EventArgs e)
{
var questionID = ((QuestionGroupBox)sender).QuestionID;
//display your question
}
Currently I use the following code to highlight the search in datagridview..but the problem is, I can't highlight the selected search..the code show below, just highlight the search that I search..So, how can I highlight search the data I want and show to the datagridview.
private void dataGridView2_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= 0 & e.ColumnIndex >= 0 & IsSelected)
{
e.Handled = true;
e.PaintBackground(e.CellBounds, true);
string sw = textBox2.Text;
if (!string.IsNullOrEmpty(sw))
{
string val = (string)e.FormattedValue;
int sindx = val.ToLower().IndexOf(sw.ToLower());
int sCount = 1;
while (sindx >= 0)
//if (sindx >= 0)
{
Rectangle hl_rect = new Rectangle();
hl_rect.Y = e.CellBounds.Y + 2;
hl_rect.Height = e.CellBounds.Height - 5;
string sBefore = val.Substring(0, sindx);
string sWord = val.Substring(sindx, sw.Length);
Size s1 = TextRenderer.MeasureText(e.Graphics, sBefore, e.CellStyle.Font, e.CellBounds.Size);
Size s2 = TextRenderer.MeasureText(e.Graphics, sWord, e.CellStyle.Font, e.CellBounds.Size);
if (s1.Width > 5)
{
hl_rect.X = e.CellBounds.X + s1.Width - 5;
hl_rect.Width = s2.Width - 6;
}
else
{
hl_rect.X = e.CellBounds.X + 2;
hl_rect.Width = s2.Width - 6;
}
SolidBrush hl_brush = default(SolidBrush);
if (((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.None))
{
hl_brush = new SolidBrush(Color.DarkGoldenrod);
}
else
{
hl_brush = new SolidBrush(Color.Yellow);
}
e.Graphics.FillRectangle(hl_brush, hl_rect);
hl_brush.Dispose();
sindx = val.ToLower().IndexOf(sw.ToLower(), sCount++);
}
}
e.PaintContent(e.CellBounds);
}
}
bool IsSelected = false;
private void SearchStringPosition(string Searchstring)
{
IsSelected = true;
}
private void btnFind_Click(object sender, EventArgs e)
{
SearchStringPosition(textBox2.Text);
dataGridView2.Refresh();
}
Please anyone...help my problem...
I have an issue regarding printing multiple pages using the code below. It always prints only the last page. Can you guys please help me?
using (var rasterizer = new PdfRasterizer(pdfInputPdf))
{
// Create a JpegImageFormat object.
var jpegImageFormat = new JpegImageFormat(100);
// Create a FixedImageSize object with required width and height.
var imageSize = new PercentageImageSize(400);
// Save the image.
var imageData = rasterizer.Draw(jpegImageFormat, imageSize);
using (var pd = new PrintDocument())
{
var margins = new Margins(0, 40, 0, 40);
pd.DefaultPageSettings.Margins = margins;
pd.DefaultPageSettings.Color = true;
pd.DefaultPageSettings.Landscape = false;
pd.PrintPage += (sender, args) =>
{
PrintPage(text1, text2, imageData, pd, args);
};
pd.Print();
}
}
And this class:
private static int counter = 0;
private static void PrintPage(string text1, string text2, byte[][] imageData, PrintPageEventArgs args)
{
foreach (var b in imageData)
{
using (var stream = new MemoryStream(b))
{
var i = Image.FromStream(stream);
CreateNotApprovedWatermark(i, text1, text2);
if (args.PageSettings.PrinterSettings.CanDuplex)
{
args.PageSettings.PrinterSettings.Duplex = Duplex.Horizontal;
}
var m = args.MarginBounds;
if (i.Width / (double)i.Height > m.Width / (double)m.Height) // image is wider
{
m.Height = (int)(i.Height / (double)i.Width * m.Width);
}
else
{
m.Width = (int)(i.Width / (double)i.Height * m.Height);
}
args.Graphics.DrawImage(i, m);
if (counter <= 2)
{
counter++;
args.HasMorePages = true;
}
else
{
args.HasMorePages = false;
}
}
}
}
I found a easy solution to my problem after quit some trial and error:
using (var rasterizer = new PdfRasterizer(new Foxit.PDF.Rasterizer.InputPdf(pdfData)))
{
// Create a JpegImageFormat object.
var jpegImageFormat = new JpegImageFormat(100);
// Create a FixedImageSize object with required width and height.
var imageSize = new PercentageImageSize(400);
// Save the image.
var imagePages = rasterizer.Draw(jpegImageFormat, imageSize);
using (var pd = new PrintDocument())
{
var margins = new Margins(0, 40, 0, 40);
pd.DefaultPageSettings.Margins = margins;
pd.DefaultPageSettings.Color = true;
pd.DefaultPageSettings.Landscape = false;
var pageNumber = 0;
pd.PrintPage += (sender, args) =>
{
PrintPage(pageNumber, text1, text2, imagePages[pageNumber], args);
if (pageNumber < imagePages.Count())
{
pageNumber++;
args.HasMorePages = pageNumber != imagePages.Count();
}
};
pd.Print();
}
}
The problem was placement of the HasMorePages property.
I've got the message above, while I'm trying to run my algorithm on more than 26 frames.
My program is in C#, with my experience with OpenCV in java(Android) I know that I need to release the matrix, do I need to do it here also?
this is the part with the problem:
private void toolStripButton2_Click(object sender, EventArgs e)
{
for (int i = 0; i < FRAME_SIZE; i++)
{
ColorImage = _Capture.QueryFrame();
if (ColorImage != null)
{
GrayImage = ColorImage.Convert<Gray, float>();
toolStripProgressBar1.Value = i;
if (i == 0)
{
Max_G2 = new Image<Gray, float>(GrayImage.Width, GrayImage.Height);
mainimage = new Image<Bgr, byte>(GrayImage.Width, GrayImage.Height);
}
FindMax(GrayImage.Copy());
}
else
{
toolStripStatusLabel1.Text = "The video is too short!";
break;
}
}
}
private void FindMax(Image<Gray, float> CurrGray)
{
Image<Gray, float> TempImg = new Image<Gray, float>(CurrGray.Width, CurrGray.Height);
Matrix<float> kernel1 = new Matrix<float>(new float[1, 2] { { -1, 1 } });
Matrix<float> kernel2 = new Matrix<float>(new float[2, 1] { { -1 }, { 1 } });
Point anchor = new Point(0, 0);
CvInvoke.cvFilter2D(CurrGray, TempImg, kernel1, anchor);
CvInvoke.cvFilter2D(CurrGray, CurrGray, kernel2, anchor);
TempImg = TempImg.Pow(2);
CurrGray = CurrGray.Pow(2);
CurrGray = CurrGray.Add(TempImg);
CurrGray = CurrGray.Pow(0.5);
Max_G2._Max(CurrGray);
}
1 more thing, I already tried to dispose all the matrix and images, but it doesn't work for me.
What do I miss here?
Thanks!
EDIT 1: ( Code with dispose)
private void toolStripButton2_Click(object sender, EventArgs e)
{
for (int i = 0; i < FRAME_SIZE; i++)
{
ColorImage = _Capture.QueryFrame();
if (ColorImage != null)
{
GrayImage = ColorImage.Convert<Gray, float>();
toolStripProgressBar1.Value = i;
if (i == 0)
{
Max_G2 = new Image<Gray, float>(GrayImage.Width, GrayImage.Height);
TempImg = new Image<Gray, float>(GrayImage.Width, GrayImage.Height);
mainimage = new Image<Bgr, byte>(GrayImage.Width, GrayImage.Height);
}
FindMax(GrayImage);
ColorImage.Dispose();
ColorImage = null;
GrayImage.Dispose();
GrayImage = null;
Thread.Sleep(100);
}
else
{
toolStripStatusLabel1.Text = "The video is too short!";
break;
}
}
}
private void FindMax(Image<Gray, float> CurrGray)
{
Matrix<float> kernel1 = new Matrix<float>(new float[1, 2] { { -1, 1 } });
Matrix<float> kernel2 = new Matrix<float>(new float[2, 1] { { -1 }, { 1 } });
Point anchor = new Point(0, 0);
CvInvoke.cvFilter2D(CurrGray, TempImg, kernel1, anchor);
CvInvoke.cvFilter2D(CurrGray, CurrGray, kernel2, anchor);
TempImg.Pow(2);
CurrGray.Pow(2);
CurrGray.Add(TempImg);
CurrGray.Pow(0.5);
Max_G2._Max(CurrGray);
CurrGray.Dispose();
CurrGray = null;
}