2023年2月9日 星期四

網頁列印實作

var mywindow = window.open("", "PRINT");
mywindow.document.body.innerHTML = '...';
$(mywindow.document.getElementById("xxx")).xxx('...'); // 使用 jquery 取得新視窗內的物件
mywindow.focus();
mywindow.print();
mywindow.close(); 

若要有分頁效果,可套用以下css
.pagebreak {
        page-break-before: always;
}

2023年2月7日 星期二

圖片處理

改變大小

※會轉為 jpeg 格式
public static byte[] resizeImage(byte[] imagearray, int maxsize)
{
using (var ms = new System.IO.MemoryStream(imagearray))
using (var image = (Image)new Bitmap(Image.FromStream(ms)))
{
decimal scale = ((decimal)image.Width) / image.Height;
Size size = default;
if (scale > 1)
{
int w = maxsize;
int h = (int)(w / scale);
size = new Size(w, h);
}
else
{
int h = maxsize;
int w = (int)(h * scale);
size = new Size(w, h);
}
byte[] arr;
Bitmap bmp = new Bitmap(image, size);
using (var ms1 = new System.IO.MemoryStream())
{
bmp.Save(ms1, ImageFormat.Jpeg);
arr = ms1.ToArray();
return arr;
}
}
}

寫入文字

var newBitmap = new Bitmap(image.Width, (int)(image.Height + fontsize));
newBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (Graphics graphics = Graphics.FromImage(newBitmap))
{
graphics.Clear(Color.White);
graphics.DrawImage(image, 0, 0);
using (Font font = new Font(fontname, fontsize, GraphicsUnit.Pixel))
{
var size = graphics.MeasureString(text, font);
var rect = new RectangleF(x, y, size.Width, size.Height);
graphics.FillRectangle(Brushes.White, rect);
graphics.DrawString(text, font, Brushes.Blue, new PointF(image.Width / 2 - fontsize * 13 / 3, image.Height - size.Height / 2));
}
}

文字轉圖片

Bitmap bmp = new Bitmap(width, Height);
using (Graphics graphics = Graphics.FromImage(bmp))
using (Font font = new Font(fontname, fontsize))
{
graphics.FillRectangle(new SolidBrush(bgcolor), 0, 0, bmp.Width, bmp.Height);
graphics.DrawString(txt, font, new SolidBrush(fcolor), 0, 0);
graphics.Flush();
}

2023年2月4日 星期六

Entity Framework 建立新物件並儲存後馬上取得關聯資料

使用 CreateProxy 建立物件,不要直接 new var newmodel = _contextXXX.CreateProxy<yyy>(); ... _contextXXX.yyy.Add(newmodel); await _contextXXX.SaveC...