Component One pdf generation using draw image crashing if printing pdf pages more than 40 - pdf

I'm using below code to generate pdf of a page having listview. And it all works good till I have a very small list once I got list with more than 50 items it crashing with memory exception. I think variable pdf is taking all memory. I have checked using profiling it goes above 180 and pdf variable was on top when I took snapshot at profile.
async PDFTest_Loaded(int a)
{
try
{
pdf = new C1PdfDocument(PaperKind.Letter);
pdf.Compression = CompressionLevel.NoCompression;
WriteableBitmap writeableBmp = await initializeImage();
List<WriteableBitmap> ListBitmaps = new List<WriteableBitmap>();
pdfPage PageBitmaps = new pdfPage();
FrameworkElement header = RTABlock as FrameworkElement;
header.Arrange(pdf.PageRectangle);
var headerImage = await CreateBitmap(header);
FrameworkElement Pageheader = SalikPaymentReceipt as FrameworkElement;
Pageheader.Arrange(pdf.PageRectangle);
var PageHeaderImage = await CreateBitmap(Pageheader);
double pdfImageWidth = 0;
foreach (var item in EpayPreviewListView.Items)
{
List<WriteableBitmap> temp = new List<WriteableBitmap>();
var obj = EpayPreviewListView.ContainerFromItem(item);
List<FrameworkElement> controls = Children(obj);
StackPanel ListItemStackPanel = controls.Where(x => x is StackPanel && x.Name == "ListItemStackPanel").First() as StackPanel;
if (ListItemStackPanel is StackPanel)
{
StackPanel itemui = ListItemStackPanel as StackPanel;
if (!(pdfImageWidth > 0))
{
pdfImageWidth = itemui.ActualWidth;
}
itemui.Arrange(new Rect(0, 0, pdfImageWidth, pdf.PageRectangle.Height));
temp.Add(await CreateBitmap(itemui));
PageBitmaps = new pdfPage() { bitmap = temp };
CreateDocumentText(pdf, headerImage, writeableBmp, PageHeaderImage, PageBitmaps);
PageBitmaps = null;
temp = new List<WriteableBitmap>();
}
}
StorageFile Assets = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Salik Payment Receipts.pdf", CreationCollisionOption.GenerateUniqueName);
PdfUtils.Save(pdf, Assets);
EpayPreviewListView.InvalidateArrange();
EpayPreviewListView.UpdateLayout();
LoadingProgress.Visibility = Visibility.Collapsed;
PrintButton.IsEnabled = true;
}
catch (Exception ex)
{
Debugger.Break();
}
}
public List<FrameworkElement> Children(DependencyObject parent)
{
try
{
var list = new List<FrameworkElement>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is StackPanel || child is TextBlock || child is ListView)
list.Add(child as FrameworkElement);
list.AddRange(Children(child));
}
return list;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString() + "\n\n" + e.StackTrace);
Debugger.Break();
return null;
}
}
async public Task<WriteableBitmap> CreateBitmap(FrameworkElement element)
{
// render element to image (WinRT)
try
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element);
var wb = new WriteableBitmap(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);
(await renderTargetBitmap.GetPixelsAsync()).CopyTo(wb.PixelBuffer);
//var rect = new Rect(0, 0, renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);
if (!App.IsEnglishSelected)
{
wb = wb.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
}
return wb;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString() + "\n\n" + ex.StackTrace);
Debugger.Break();
return new WriteableBitmap(0, 0);
}
}
bool isFirst = true;
void CreateDocumentText(C1PdfDocument pdf, WriteableBitmap headerImage, WriteableBitmap writeableBmp, WriteableBitmap pageHeading, pdfPage ListItem)
{
try
{
if (!isFirst)
{
pdf.NewPage();
}
isFirst = false;
pdf.Landscape = false;
double contentHeight = 0;
double leftMargin = 0;
string fontName = "Arial";
// measure and show some text
var text = App.GetResource("RoadandTransportAuthority");
var font = new Font(fontName, 36, PdfFontStyle.Bold);
// create StringFormat used to set text alignment and line spacing
var fmt = new StringFormat();
fmt.Alignment = HorizontalAlignment.Center;
var rc = new Rect(0, 0,
pdf.PageRectangle.Width, headerImage.PixelHeight);
pdf.DrawImage(headerImage, rc, ContentAlignment.MiddleCenter, Stretch.None);
contentHeight += headerImage.PixelHeight + 2;
rc = new Rect(0, contentHeight, pdf.PageRectangle.Width, writeableBmp.PixelHeight);
pdf.DrawImage(writeableBmp, rc);
contentHeight += writeableBmp.PixelHeight + 5;
rc = new Rect(leftMargin, contentHeight,
pdf.PageRectangle.Width,
pageHeading.PixelHeight);
pdf.DrawImage(pageHeading, rc, ContentAlignment.MiddleCenter, Stretch.None);
contentHeight += pageHeading.PixelHeight + 2;
Debug.WriteLine(ListItem.bitmap.Count.ToString());
for (int i = 0; i < ListItem.bitmap.Count; i++)
{
rc = PdfUtils.Offset(rc, 0, rc.Height + 10);
rc.Height = ListItem.bitmap.ElementAt(i).PixelHeight;
pdf.DrawImage(ListItem.bitmap.ElementAt(i), rc, ContentAlignment.TopCenter, Stretch.None);
ListItem.bitmap[i] = null;
}
ListItem = null;
}
catch (Exception e)
{
//...
}
}

It is due to memory clash I have to decrease the quality of images to handle it. Also it takes some time to release memory.

Related

File provider error to receive pdf from another program

`# Dears, this class works well to receive PDF files from another application on below Android 6, but it gives an error for Android uper 6
` #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public int ExtractImage(Intent intent) {
try {
String filepath = null;
if (intent != null) {
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {
Uri file_uri = intent.getData();
if (file_uri != null) {
filepath = file_uri.getPath();
}
} else if (Intent.ACTION_SEND.equals(action) && type.endsWith("pdf")) {
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null) {
filepath = uri.getPath();
}
}
}
File file = new File(filepath);
PdfRenderer renderer = null;
Bitmap bm;
try {
renderer = new PdfRenderer(ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_ONLY));
} catch (Exception e) {
}
assert renderer != null;
final int pageCount = renderer.getPageCount();
totalPage = pageCount;
for (int i = 0; i < pageCount; i++) {
PdfRenderer.Page page = renderer.openPage(i);
// Create a bitmap and canvas to draw the page into
int width = 570;
int zarib = 570 / (page.getWidth() + 1);
int height = (page.getHeight() * 2) + 1;
heightArray.add(i, height);
// Create a bitmap and canvas to draw the page into
bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// Create canvas to draw into the bitmap
Canvas c = new Canvas(bm);
// Fill the bitmap with a white background
Paint whiteBgnd = new Paint();
whiteBgnd.setColor(Color.WHITE);
whiteBgnd.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, width, height, whiteBgnd);
// paint the page into the canvas
page.render(bm, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
// Save the bitmap
OutputStream outStream = null;
try {
outStream = new
FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/printDo2ta" + i + ".png");
} catch (Exception e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.PNG, 80, outStream);
try {
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
page.close();
}
} catch (Exception e) {
runOnUiThread(() -> Toast.makeText(getBaseContext(),
"خطا در پردازش فایل: " + e.getMessage(),
Toast.LENGTH_SHORT).show());
}
return totalPage;
}
I inserted this code in AndroidManifest.xml
`<provider
android:name="androidx.core.content.FileProvider"
android:authorities="ir.myproject.test.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>`
`
And I made the class provider_paths.xml
`<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>`
I don't know what else I need to change to make it work on Android 8
please help me`

Hearing Clipping after using NAudio MixingSampleProvider

I'm hoping someone can help me. I am using NAudio and am recording from multiple wsapiloopbackcapture devices and mixing them together. None of this can be written to disk, so I am doing it all in memory and am ultimately loading the data into a concurrent dictionary for another process to use that I will develop later. All this works except that whenever I run my thread to load my chunk data into my dictionary, when I play the audio back I hear a single clip sound and it coincides with how often I run the thread. If I set it to run every 20 seconds then I hear a clip sound at the 20 second mark when I listen to the audio. I need to get rid of this clipping and I can't figure out what is causing it.
Here are the basic steps
private static WasapiLoopbackCapture Wavein = null;
private static WasapiLoopbackCapture Wavein2 = null;
private static WaveFormat pcm8k16bitSt = new WaveFormat(8000, 16, 2);
private static WaveFormat pcm8k16bitMo = new WaveFormat(8000, 16, 1);
private static WaveFormat Bit16;
private static byte[] DataHeader = System.Text.Encoding.UTF8.GetBytes("data");
private static List<byte> SBL = new List<byte>();
private static List<byte> SBL2 = new List<byte>();
private static byte[] chunkdata;
private static byte[] chunkdata2;
internal static ConcurrentDictionary<DateTime, DataFrame> AllSpeakerBytes = new ConcurrentDictionary<DateTime, DataFrame>();
int SdeviceNumber = 0;
int SdeviceNumber2 = 0;
private static MMDevice deviceToRecord = null;
private static MMDevice deviceToRecord2 = null;
deviceToRecord = (new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active))[SdeviceNumber];
deviceToRecord2 = (new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active))[SdeviceNumber2];
RecordAllSpeakers();
private void RecordAllSpeakers()
{
if (deviceToRecord != null)
{
Wavein = new WasapiLoopbackCapture(deviceToRecord);
var silence = new SilenceProvider(Wavein.WaveFormat).ToSampleProvider();
var wo = new WaveOutEvent();
wo.DeviceNumber = SdeviceNumber;
wo.Init(silence);
wo.Play();
Wavein.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(SsourceStream_DataAvailable);
Wavein.StartRecording();
SRecFlag = true;
}
if (deviceToRecord2 != null)
{
Wavein2 = new WasapiLoopbackCapture(deviceToRecord2);
var silence = new SilenceProvider(Wavein2.WaveFormat).ToSampleProvider();
var wo = new WaveOutEvent();
wo.DeviceNumber = SdeviceNumber2;
wo.Init(silence);
wo.Play();
Wavein2.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(SsourceStream2_DataAvailable);
Wavein2.StartRecording();
SRecFlag2 = true;
}
}
private void SsourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (!SRecFlag) return;
if (Wavein.WaveFormat.BitsPerSample == 32)
{
#region NewStraightConvert
using (RawSourceWaveStream RS = new RawSourceWaveStream(e.Buffer, 0, e.BytesRecorded, WaveFormat.CreateIeeeFloatWaveFormat(Wavein.WaveFormat.SampleRate, Wavein.WaveFormat.Channels)))
using (Wave32To16Stream wav16 = new Wave32To16Stream(RS))
using (MemoryStream ms2 = new MemoryStream())
{
WaveFileWriter.WriteWavFileToStream(ms2, wav16);
ms2.Position = 0;
using (var reader = new WaveFileReader(ms2))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
byte[] SendingBytes;
using (MemoryStream ms3 = new MemoryStream())
{
using (RawSourceWaveStream cc = new RawSourceWaveStream(conversionStream1, pcm8k16bitMo))
{
cc.Position = 0;
cc.CopyTo(ms3);
SendingBytes = ms3.ToArray();
}
}
if (SendingBytes.Length > 0)
{
//SslTcpClient.VociDataToSendST2.AddRange(SendingBytes);
SBL.AddRange(SendingBytes);
}
}
}
#endregion
return;
}
else
{
byte[] outtovoci;
Bit16 = new WaveFormat(Wavein.WaveFormat.SampleRate, 16, Wavein.WaveFormat.Channels);
outtovoci = new byte[e.BytesRecorded];
Array.Copy(e.Buffer, 0, outtovoci, 0, e.BytesRecorded);
using (MemoryStream TESTWaveMS = new MemoryStream())
{
using (MemoryStream TESTWaveMS2 = new MemoryStream())
{
using (WaveFileWriter TESTwaveWriter = new WaveFileWriter(TESTWaveMS, Bit16))
{
TESTwaveWriter.Write(outtovoci, 0, outtovoci.Length);
TESTwaveWriter.Flush();
byte[] tbytes = TESTWaveMS.ToArray();
using (MemoryStream tstream = new MemoryStream(tbytes))
{
using (var reader = new WaveFileReader(tstream))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
WaveFileWriter.WriteWavFileToStream(TESTWaveMS2, conversionStream1);
byte[] tbytes2 = TESTWaveMS2.ToArray();
int fPos = SearchBytes(tbytes2, DataHeader);
if (fPos > 0)
{
fPos = fPos + 8;
}
else
{
fPos = 0;
}
long SendingBytes = tbytes2.Length - fPos;
byte[] WBack = new byte[SendingBytes];
if (SendingBytes > 0)
{
Array.Copy(tbytes2, fPos, WBack, 0, SendingBytes);
//SslTcpClient.VociDataToSendST2.AddRange(WBack);
SBL.AddRange(WBack);
}
}
}
}
}
}
}
}
private void SsourceStream2_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (!SRecFlag2) return;
if (Wavein2.WaveFormat.BitsPerSample == 32)
{
#region NewStraightConvert
using (RawSourceWaveStream RS = new RawSourceWaveStream(e.Buffer, 0, e.BytesRecorded, WaveFormat.CreateIeeeFloatWaveFormat(Wavein2.WaveFormat.SampleRate, Wavein2.WaveFormat.Channels)))
using (Wave32To16Stream wav16 = new Wave32To16Stream(RS))
using (MemoryStream ms2 = new MemoryStream())
{
WaveFileWriter.WriteWavFileToStream(ms2, wav16);
ms2.Position = 0;
using (var reader = new WaveFileReader(ms2))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
byte[] SendingBytes;
using (MemoryStream ms3 = new MemoryStream())
{
using (RawSourceWaveStream cc = new RawSourceWaveStream(conversionStream1, pcm8k16bitMo))
{
cc.Position = 0;
cc.CopyTo(ms3);
SendingBytes = ms3.ToArray();
}
}
if (SendingBytes.Length > 0)
{
//SslTcpClient.VociDataToSendST2.AddRange(SendingBytes);
SBL2.AddRange(SendingBytes);
}
}
}
#endregion
return;
}
else
{
byte[] outtovoci;
Bit16 = new WaveFormat(Wavein2.WaveFormat.SampleRate, 16, Wavein2.WaveFormat.Channels);
outtovoci = new byte[e.BytesRecorded];
Array.Copy(e.Buffer, 0, outtovoci, 0, e.BytesRecorded);
using (MemoryStream TESTWaveMS = new MemoryStream())
{
using (MemoryStream TESTWaveMS2 = new MemoryStream())
{
using (WaveFileWriter TESTwaveWriter = new WaveFileWriter(TESTWaveMS, Bit16))
{
TESTwaveWriter.Write(outtovoci, 0, outtovoci.Length);
TESTwaveWriter.Flush();
byte[] tbytes = TESTWaveMS.ToArray();
using (MemoryStream tstream = new MemoryStream(tbytes))
{
using (var reader = new WaveFileReader(tstream))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
WaveFileWriter.WriteWavFileToStream(TESTWaveMS2, conversionStream1);
byte[] tbytes2 = TESTWaveMS2.ToArray();
int fPos = SearchBytes(tbytes2, DataHeader);
if (fPos > 0)
{
fPos = fPos + 8;
}
else
{
fPos = 0;
}
long SendingBytes = tbytes2.Length - fPos;
byte[] WBack = new byte[SendingBytes];
if (SendingBytes > 0)
{
Array.Copy(tbytes2, fPos, WBack, 0, SendingBytes);
//SslTcpClient.VociDataToSendST2.AddRange(WBack);
SBL2.AddRange(WBack);
}
}
}
}
}
}
}
}
private async void timer3_Tick(object sender, EventArgs e)
{
timer3.Enabled = false;
if (SRecFlag == true || SRecFlag2 == true)
{
await Task.Run(() => SyncSpeakers());
}
timer3.Interval = 20000;
timer3.Enabled = true;
}
private static void SyncSpeakers()
{
MemoryStream ms = new MemoryStream();
MemoryStream ms2 = new MemoryStream();
WaveFileReader reader = null;
WaveFileReader reader2 = null;
MixingSampleProvider mixer = null;
int lbc = SBL.Count();
int lbc2 = SBL2.Count();
int lowest = 0;
int[] array = new int[] { lbc, lbc2 };
lowest = array.Where(f => f > 0).Min();
if (deviceToRecord != null && SBL.Count > 0)
{
chunkdata = new byte[lowest];
Array.Copy(SBL.ToArray(), 0, chunkdata, 0, chunkdata.Length);
SwaveWriterS1 = new NAudio.Wave.WaveFileWriter(ms, pcm8k16bitMo);
SwaveWriterS1.Write(chunkdata, 0, chunkdata.Length);
SwaveWriterS1.Flush();
SBL.RemoveRange(0, lowest);
}
if (deviceToRecord2 != null && SBL2.Count > 0)
{
chunkdata2 = new byte[lowest];
Array.Copy(SBL2.ToArray(), 0, chunkdata2, 0, chunkdata2.Length);
SwaveWriterS2 = new NAudio.Wave.WaveFileWriter(ms2, pcm8k16bitMo);
SwaveWriterS2.Write(chunkdata2, 0, chunkdata2.Length);
SwaveWriterS2.Flush();
SBL2.RemoveRange(0, lowest);
}
int SWaves = 0;
if (Wavein != null && SRecFlag == true)
{
ms.Position = 0;
reader = new WaveFileReader(ms);
SWaves++;
}
if (Wavein2 != null && SRecFlag2 == true)
{
ms2.Position = 0;
reader2 = new WaveFileReader(ms2);
SWaves++;
}
if (SWaves == 1)
{
mixer = new MixingSampleProvider(new[] { reader.ToSampleProvider() });
}
else if (SWaves == 2)
{
mixer = new MixingSampleProvider(new[] { reader.ToSampleProvider(), reader2.ToSampleProvider() });
}
if (SWaves > 0)
{
using (MemoryStream lms = new MemoryStream())
{
WaveFileWriter.WriteWavFileToStream(lms, mixer.ToWaveProvider16());
byte[] SendingBytes;
using (MemoryStream ms35 = new MemoryStream())
{
using (RawSourceWaveStream cc = new RawSourceWaveStream(lms, pcm8k16bitMo))
{
cc.Position = 0;
cc.CopyTo(ms35);
SendingBytes = ms35.ToArray();
SwaveWriter.Write(SendingBytes, 0, SendingBytes.Length);
SwaveWriter.Flush();
byte[] lByte = Compress(SendingBytes);
DataFrame aFrame2 = new DataFrame();
aFrame2.bytes = new byte[lByte.Length];
aFrame2.bytesRecorded = SendingBytes.Length;
lByte.CopyTo(aFrame2.bytes, 0);
AllSpeakerBytes.TryAdd(DateTime.UtcNow, aFrame2);
lByte = null;
}
}
}
}
}
internal static byte[] Compress(byte[] data)
{
try
{
//return data;
using (MemoryStream output = new MemoryStream())
{
using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))
{
dstream.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
catch (Exception ERR5)
{
//Logging.LogData($"Failure in Compress: {ERR5.ToString()}");
return null;
}
}
internal static byte[] Decompress(byte[] data)
{
//return data;
try
{
using (MemoryStream output = new MemoryStream())
{
using (MemoryStream input = new MemoryStream(data))
{
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
}
return output.ToArray();
}
}
catch (Exception ERR5)
{
//Logging.LogData($"Failure in Decompress: {ERR5.ToString()}");
return null;
}
}
class DataFrame
{
public byte[] bytes { get; set; }
public int bytesRecorded { get; set; }
public string extraData { get; set; } = "";
}
private void btnStop_Click(object sender, EventArgs e)
{
if (Wavein != null)
{
Wavein.StopRecording();
Wavein.Dispose();
Wavein = null;
}
if (Wavein2 != null)
{
Wavein2.StopRecording();
Wavein2.Dispose();
Wavein2 = null;
}
mp3WriterAllSpk = new NAudio.Lame.LameMP3FileWriter(FinalSRFilename, pcm8k16bitMo, 64);
List<DateTime> SpkWrites = AllSpeakerBytes.Select(k => k.Key).OrderBy(c => c).ToList();
foreach (DateTime DT in SpkWrites)
{
byte[] outgoing = Decompress(AllSpeakerBytes[DT].bytes);
mp3WriterAllSpk.Write(outgoing, 0, AllSpeakerBytes[DT].bytesRecorded);
}
mp3WriterAllSpk.Dispose();
SRecFlag = false;
SRecFlag2 = false;
}
This code needs a lot of cleaning up but basically the SyncSpeakers() is being ran every 20 seconds and I am hearing a clipping at 20 second increments of the audio. If I change the timer to run every 10 seconds I will hear a clip sound every 10 seconds of the resulting audio. Any ideas?
I was able to solve this by shaving the first 100 bytes off of the front and replacing them with byte 101. If there is a better way I'd love to hear it.
Thanks!

Screenshot using SharpDX and EasyHook transparent

I have been struggling in taking screenshots with DirectX, the problem is, it's working but seems to be missing some colors (black outline is missing for example), and some stuff that is also rendered by DX doesn't show.
I have uploaded the images (how the image should render and the rendered one) and also the code, what might be the issue?
Correct Image
Rendered Image
Greetings
public class Screenshot
{
public static void TakeScreenshot(string name = null)
{
var t = new Thread((ThreadStart) delegate
{
// destination folder
var destinationFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.Create) + "\\My Software\\Screenshots";
if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder);
// file name
string filename = name;
if (string.IsNullOrEmpty(name))
filename = "image-" + (Directory.GetFiles(destinationFolder, "*.png").Count() + 1).ToString("000") + ".png";
// # of graphics card adapter
const int numAdapter = 0;
// # of output device (i.e. monitor)
const int numOutput = 0;
// Create DXGI Factory1
var factory = new Factory1();
var adapter = factory.GetAdapter1(numAdapter);
// Create device from Adapter
var device = new Device(adapter);
// Get DXGI.Output
var output = adapter.GetOutput(numOutput);
var output1 = output.QueryInterface<Output1>();
// Width/Height of desktop to capture
int width = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width;
int height = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height;
// Create Staging texture CPU-accessible
var textureDesc = new Texture2DDescription
{
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = width,
Height = height,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
var screenTexture = new Texture2D(device, textureDesc);
// Duplicate the output
var duplicatedOutput = output1.DuplicateOutput(device);
bool captureDone = false;
for (int i = 0; !captureDone; i++)
{
try
{
SharpDX.DXGI.Resource screenResource;
OutputDuplicateFrameInformation duplicateFrameInformation;
// Try to get duplicated frame within given time
duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource);
if (i > 0)
{
// copy resource into memory that can be accessed by the CPU
using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
// Get the desktop capture texture
var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);
// Create Drawing.Bitmap
var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);
// Copy pixels from screen capture Texture to GDI bitmap
var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
var sourcePtr = mapSource.DataPointer;
var destPtr = mapDest.Scan0;
for (int y = 0; y < height; y++)
{
// Copy a single line
Utilities.CopyMemory(destPtr, sourcePtr, width * 4);
// Advance pointers
sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
destPtr = IntPtr.Add(destPtr, mapDest.Stride);
}
// Release source and dest locks
bitmap.UnlockBits(mapDest);
device.ImmediateContext.UnmapSubresource(screenTexture, 0);
// Save the output
bitmap.Save(destinationFolder + Path.DirectorySeparatorChar + filename);
// Send Message
Main.Chat.AddMessage(null, "~b~Screenshot saved as " + filename);
// Capture done
captureDone = true;
}
screenResource.Dispose();
duplicatedOutput.ReleaseFrame();
}
catch (SharpDXException e)
{
if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
{
throw e;
}
}
}
});
t.IsBackground = true;
t.Start();
}
}

Label Printing using iTextSharp

I have a logic to export avery label pdf. The logic exports the pdf with labels properly but when i print that pdf, the page size measurements (Page properties) that i pass isn't matching with the printed page.
Page Properties
Width="48.5" Height="25.4" HorizontalGapWidth="0" VerticalGapHeight="0" PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8" PageSize="A4" LabelsPerRow="4" LabelRowsPerPage="10"
The above property values are converted equivalent to point values first before applied.
Convert to point
private float mmToPoint(double mm)
{
return (float)((mm / 25.4) * 72);
}
Logic
public Stream SecLabelType(LabelProp _label)
{
List<LabelModelClass> Model = new List<LabelModelClass>();
Model = RetModel(_label);
bool IncludeLabelBorders = false;
FontFactory.RegisterDirectories();
Rectangle pageSize;
switch (_label.PageSize)
{
case "A4":
pageSize = iTextSharp.text.PageSize.A4;
break;
default:
pageSize = iTextSharp.text.PageSize.A4;
break;
}
var doc = new Document(pageSize,
_label.PageMarginLeft,
_label.PageMarginRight,
_label.PageMarginTop,
_label.PageMarginBottom);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, output);
writer.CloseStream = false;
doc.Open();
var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
var tbl = new PdfPTable(numOfCols);
var colWidths = new List<float>();
for (int i = 1; i <= numOfCols; i++)
{
if (i % 2 > 0)
{
colWidths.Add(_label.Width);
}
else
{
colWidths.Add(_label.HorizontalGapWidth);
}
}
var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
var size = new iTextSharp.text.Rectangle(w, h);
tbl.SetWidthPercentage(colWidths.ToArray(), size);
//var val = System.IO.File.ReadLines("C:\\Users\\lenovo\\Desktop\\test stock\\testing3.txt").ToArray();
//var ItemNoArr = Model.Select(ds => ds.ItemNo).ToArray();
//string Header = Model.Select(ds => ds.Header).FirstOrDefault();
int cnt = 0;
bool b = false;
int iAddRows = 1;
for (int iRow = 0; iRow < ((Model.Count() / _label.LabelsPerRow) + iAddRows); iRow++)
{
var rowCells = new List<PdfPCell>();
for (int iCol = 1; iCol <= numOfCols; iCol++)
{
if (Model.Count() > cnt)
{
if (iCol % 2 > 0)
{
var cellContent = new Phrase();
if (((iRow + 1) >= _label.StartRow && (iCol) >= (_label.StartColumn + (_label.StartColumn - 1))) || b)
{
b = true;
try
{
var StrArr = _label.SpineLblFormat.Split('|');
foreach (var x in StrArr)
{
string Value = "";
if (x.Contains(","))
{
var StrCommaArr = x.Split(',');
foreach (var y in StrCommaArr)
{
if (y != "")
{
Value = ChunckText(cnt, Model, y, Value);
}
}
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
else
{
Value = ChunckText(cnt, Model, x, Value);
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
}
}
catch (Exception e)
{
var fontHeader1 = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 6, 0);
cellContent.Add(new Chunk("NA", fontHeader1));
}
cnt += 1;
}
else
iAddRows += 1;
var cell = new PdfPCell(cellContent);
cell.FixedHeight = _label.Height;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;
rowCells.Add(cell);
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
_label.LabelRowsPerPage = _label.LabelRowsPerPage == null ? 0 : _label.LabelRowsPerPage;
if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
{
tbl.Rows.Add(CreateGapRow(numOfCols, _label));
}
}
doc.Add(tbl);
doc.Close();
output.Position = 0;
return output;
}
private PdfPRow CreateGapRow(int numOfCols, LabelProp _label)
{
var cells = new List<PdfPCell>();
for (int i = 0; i < numOfCols; i++)
{
var cell = new PdfPCell();
cell.FixedHeight = _label.VerticalGapHeight;
cell.Border = Rectangle.NO_BORDER;
cells.Add(cell);
}
return new PdfPRow(cells.ToArray());
}
A PDF document may have very accurate measurements, but then those measurements get screwed up because the page is scaled during the printing process. That is a common problem: different printers will use different scaling factors with different results when you print the document using different printers.
How to avoid this?
In the print dialog of Adobe Reader, you can choose how the printer should behave:
By default, the printer will try to "Fit" the content on the page, but as not every printer can physically use the full page size (due to hardware limitations), there's a high chance the printer will scale the page down if you use "Fit".
It's better to choose the option "Actual size". The downside of using this option is that some content may get lost because it's too close to the border of the page in an area that physically can't be reached by the printer, but the advantage is that the measurements will be preserved.
You can set this option programmatically in your document by telling the document it shouldn't scale:
writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
See How to set initial view properties? for more info about viewer preferences.

how to reduce the size of multiple images before save to database using asp.net fileuploader

I have done the multiple file up-loader and save the images in database as (byte)
while retrieving those all images memory out of exception was thrown so i want to reduce the size of uploaded multiple files through pragmatically (c#,asp.net)
with that i have problem with reducing the sizes of multiple images using file up-loader in .net before saving to database
protected void DataUploading()
{
try
{
int count;
if (uploader.HasFile)
{
string s = System.IO.Path.GetExtension(uploader.FileName);
if ((s == ".JPG") || (s == ".JPEG") || (s == ".PNG") || (s == ".BMP") || (s == ".jpg") || (s == ".jpeg") || (s == ".png") || (s == ".bmp") || (s == ".jpe"))
{
count = ReferrenceCount();
HttpFileCollection fileCollection = Request.Files;
if (count == 0)
{
count = 0;
}
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
int fileSize = uploadfile.ContentLength;
if (fileSize <= 31457280)//3145728-5242880
{
string fileName = Path.GetFileName(uploadfile.FileName);
if (uploadfile.ContentLength > 0)
{
string contentType = uploader.PostedFile.ContentType;
using (Stream fs = uploadfile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
byte[] newbytes = reducesize(uploadfile);
imagelist.Add(bytes);
refcounts.Add(count);
count += 1;
}
}
}
}
else
{
//image compression code to be written here
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('FILE SIZE SHOULD BE LIMIT TO 5MB')", true);
}
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('ONLY JPEG,BMP,PNG ARE ALLOWED')", true);
}
for (int ij = 0; ij < imagelist.Count; ij++)
{
using (con = new SqlConnection(constr))
{
string query = string.Empty;
query = "INSERT INTO INVENTORY_IMAGES(CLAIM_NUMBER,PHOTOS,REF_NO,UPDATEDATE,MODIFIEDDATE,MODIFIEDBY,CHASSIS) values (#Name, #Data,#REF,#DATE,#datetime,#user,#chassis)";
using (cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", txtclaimnumber.Text);
cmd.Parameters.AddWithValue("#Data", imagelist[ij]);
cmd.Parameters.AddWithValue("#REF", refcounts[ij].ToString());
cmd.Parameters.AddWithValue("#DATE", DateTime.Now.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#datetime", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#user", Session["user"].ToString());
cmd.Parameters.AddWithValue("#chassis", txtchasisno.Text);
con.Open();
cmd.ExecuteNonQuery();//'"+DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")+"','"+Session["user"].ToString()+"','"++"'
}
}
}
imagelist.Clear();
refcounts.Clear();
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('PLEASE SELECT A FILE')", true);
}
}
catch (Exception ee)
{
WriteLog(ee.Message);
throw ee;
}
}
private byte[] reducesize(HttpPostedFile HttpPostedFiles)
{
//variable to store the image content
//the size of the variable is initialized to the file content length
byte[] imageBytes = new byte[HttpPostedFiles.ContentLength];
//Gets the underlying System.Web.HttpPostedFile object for a file that is uploaded
//by using the System.Web.UI.WebControls.FileUpload control.
//HttpPostedFile uploadImage = fileUploadS.PostedFile;
//read the image stream from the post and store it in imageBytes
HttpPostedFiles.InputStream.Read(imageBytes, 0, (int)HttpPostedFiles.ContentLength);
//resize image to a thumbnail
MemoryStream thumbnailPhotoStream = ResizeImage(HttpPostedFiles);
byte[] thumbnailImageBytes = thumbnailPhotoStream.ToArray();
return thumbnailImageBytes;
//end
}
private MemoryStream ResizeImage(HttpPostedFile HttpPostedFiless)
{
try
{
Bitmap originalBMP = new Bitmap(HttpPostedFiless.InputStream);
// Create a bitmap with the uploaded file content
//Bitmap originalBMP = new Bitmap(inputContent);
// get the original dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
//calculate the current aspect ratio
int aspectRatio = origWidth / origHeight;
//if the aspect ration is less than 0, default to 1
if (aspectRatio <= 0)
aspectRatio = 1;
//new width of the thumbnail image
int newWidth = 100;
//calculate the height based on the aspect ratio
int newHeight = newWidth / aspectRatio;
// Create a new bitmap to store the new image
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics graphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
graphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
//save the bitmap into a memory stream
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, GetImageFormat(System.IO.Path.GetExtension(HttpPostedFiless.FileName)));
// dispose drawing objects
originalBMP.Dispose();
newBMP.Dispose();
graphics.Dispose();
return stream;
}
catch (Exception ee)
{
WriteLog(ee.Message);
throw;
}
}
private System.Drawing.Imaging.ImageFormat GetImageFormat(string extension)
{
switch (extension.ToLower())
{
case "jpg":
return System.Drawing.Imaging.ImageFormat.Jpeg;
case "bmp":
return System.Drawing.Imaging.ImageFormat.Bmp;
case "png":
return System.Drawing.Imaging.ImageFormat.Png;
}
return System.Drawing.Imaging.ImageFormat.Jpeg;
}