I have requirement of online cheque generation.
I am using ,
using iTextSharp.text;
using iTextSharp.text.pdf;
I have dynamic cheque Height and width,font and fontsize.
And obviously cheque number with account information in all page of document.
My code goes like this
Document doc = new Document(new Rectangle(width, height), 0, 0, 0, 0);
string path = Server.MapPath("~/REPORTFILES");
var writer = PdfWriter.GetInstance(doc, new FileStream(path + "/cheque.pdf",FileMode.Create));
doc.Open();
BaseFont f_cn = BaseFont.CreateFont("c:\\windows\\fonts\\calibri.ttf", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
for (int i = fromchq; i <= tochq; i++)
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
cb.SetFontAndSize(f_cn, 14);
cb.SetFontAndSize(f_cn, fontsize);
cb.SetTextMatrix(cord_x, cord_y);
cb.ShowText(getProperty(propertyName,i.ToString().PadLeft(FromChqNo.Length, '0')));
cb.EndText();
doc.NewPage();
}
Here cord_x and cord_y is the co-ordinate location of that text.
Everything works fine i got pdf of my custom size.
like this :
But while printing it into the cheque
its work fine untill it has space enough to print single page. my xps image is attached bellow.
Area in red curve is skiped to be printed.
I mean to ask how can i make it posible that it will print serially, and completely fullfill my requirement that a cheque leaf of any height ,width,font will be printed serially. Thank you all in advance and also thanks for reading my problem.
Related
Is it possible to scale a page from e.g. A2 to A1 with PDFsharp?
I can set the size of the page via Size, Width and Height. But how can I scale the content of the page?
based on the comment from Vive and the link provided there, here an example for resizing to A4 with C#:
you must include:
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp;
then:
// resize this file from A3 to A4
string filename = #"C:\temp\A3.pdf";
// Create the new output document (A4)
PdfDocument outputDocument = new PdfDocument();
outputDocument.PageLayout = PdfPageLayout.SinglePage;
XGraphics gfx;
XRect box;
// Open the file to resize
XPdfForm form = XPdfForm.FromFile(filename);
// Add a new page to the output document
PdfPage page = outputDocument.AddPage();
if (form.PixelWidth > form.PixelHeight)
page.Orientation = PageOrientation.Landscape;
else
page.Orientation = PageOrientation.Portrait;
double width = page.Width;
double height = page.Height;
gfx = XGraphics.FromPdfPage(page);
box = new XRect(0, 0, width, height);
gfx.DrawImage(form, box);
// Save the document...
string newfilename = #"c:\temp\resized.pdf";
outputDocument.Save(newfilename);
You can use DrawImage() to draw an existing PDF page on a new PDF page. You can specify the destination rectangle and thus you can scale the page as needed.
Use the XPdfForm class to access the existing PDF file.
See the Two Pages on One sample for details:
http://www.pdfsharp.net/wiki/TwoPagesOnOne-sample.ashx
I have generated some PDF report using MigraDoc. Initial code is as follows:-
MigraDoc.DocumentObjectModel.Document document = new MigraDoc.DocumentObjectModel.Document();
MigraDoc.DocumentObjectModel.Section section = document.AddSection();
...
Paragraph paragraph = section.Headers.Primary.AddParagraph();
....
table = section.AddTable();
...
paragraph = section.Footers.Primary.AddParagraph();
...
The PDF was rendered successfully. Now I want to add some graphics into the pages of this document. I have gone through several articles for that and found that everyone using PdfDocument class instead of MigraDoc.DocumentObjectModel.Document. Is it possible to apply graphics into pages of a document of type MigraDoc.DocumentObjectModel.Document using XGraphics? If it is not possible, what is the best way to mix PdfDocument with MigraDoc.DocumentObjectModel.Document to accomplish the same?
MigraDoc uses PDFsharp and an XGraphics object to create the PDF pages.
There are several ways to add content to pages created by MigraDoc.
This MigraDoc sample shows some options:
http://pdfsharp.net/wiki/MixMigraDocAndPdfSharp-sample.ashx
You can even call MigraDoc to use "your" XGraphics object for drawing:
// Alternative rendering with progress indicator.
// Set a callback for phase 1.
pdfRenderer.DocumentRenderer.PrepareDocumentProgress += PrepareDocumentProgress;
// Now start phase 1: Preparing pages (i.e. calculate the layout).
pdfRenderer.PrepareRenderPages();
// Now phase 2: create the PDF pages.
Console.WriteLine("\r\nRendering document ...");
int pages = pdfRenderer.DocumentRenderer.FormattedDocument.PageCount;
for (int i = 1; i <= pages; ++i)
{
var page = pdfRenderer.PdfDocument.AddPage();
Console.Write("\rRendering page " + i + "/" + pages);
PageInfo pageInfo = pdfRenderer.DocumentRenderer.FormattedDocument.GetPageInfo(i);
page.Width = pageInfo.Width;
page.Height = pageInfo.Height;
page.Orientation = pageInfo.Orientation;
using (XGraphics gfx = XGraphics.FromPdfPage(page))
{
gfx.MUH = pdfRenderer.Unicode ? PdfFontEncoding.Unicode : PdfFontEncoding.WinAnsi;
gfx.MFEH = pdfRenderer.FontEmbedding;
pdfRenderer.DocumentRenderer.RenderPage(gfx, i);
}
}
Console.WriteLine("\r\nSaving document ...");
Sample code taken from this post:
http://forum.pdfsharp.net/viewtopic.php?p=9293#p9293
I am trying to increase the size of an uploaded image using system.drawing. It works but the file sizes are much larger than if I were to do this using Photoshop. Is this something I will have to cope with or is there a way to decrease the file size?
I am using this code, and have tweaked the Drawing2d settings but it doesn't make an appreciable difference.
resizedImage = New Bitmap(newWidth, newHeight, image.PixelFormat)
graphics = graphics.FromImage(resizedImage)
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality
graphics.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
graphics.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
graphics.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight)
graphics.DrawImage(image, 0, 0, newWidth, newHeight)
Do I need to use a dedicated library for this to achieve better results?
The parameters you have here are affect the "rendering" of the image, not the "image file size".
To affect the image file size, you need to drop down the quality of the jpeg when you save it, using the Image.Save Method
This is a snipped code from the MSDN Example on how you can drop down the image file size.
// Save the bitmap as a JPEG file with quality level 25.
myEncoderParameter = new EncoderParameter(myEncoder, 25L);
myEncoderParameters.Param[0] = myEncoderParameter;
// and now save it to the file
myBitmap.Save("Shapes025.jpg", myImageCodecInfo, myEncoderParameters);
I am using iTextSharp to join multiple pdfs together that are from microsofts report viewer. page.AddImage(image__1) in the code below is throwing an error Object reference not set to an instance of an object. I am not seeing what is set to nothing. Is there a different way that I can join reports from the report viewer and add a watermark image?
mybytes = MSRptViewer1.LocalReport.Render("PDF", Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
reader = New iTextSharp.text.pdf.PdfReader(mybytes)
numberOfPages = reader.NumberOfPages
currentPageNumber = 0
Dim imageFile As String = Server.MapPath("WaterMark.png")
Dim buffer As Byte() = IO.File.ReadAllBytes(imageFile)
Dim image__1 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(buffer)
image__1.SetAbsolutePosition(100, 100)
Do While (currentPageNumber < numberOfPages)
currentPageNumber += 1
doc.SetPageSize(PageSize.LETTER)
doc.NewPage()
page = writer.GetImportedPage(reader, currentPageNumber)
page.AddImage(image__1)
rotation = reader.GetPageRotation(currentPageNumber)
If (rotation = 90) Or (rotation = 270) Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(currentPageNumber).Height)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
Loop
<?php $data = file_get_contents('https://static1.squarespace.com/static/56c775ad27d4bd3fdb24775d/t/5a8b201324a694d7071662ee/1519067160925/dummy+logo.jpg');
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
?>
this method for image convert to base64 format
<?php echo '<div class="company-logo"><img src="'.$base64.'" alt="base" /></div>'; ?>
or
<img src="<?php echo $base64; ?>" alt="base" />
I have asked my Publisher, Manning Publications, to offer chapter 6 of my book for free. I know this chapter only shows you examples in Java, but all the examples were ported to C# for your convenience.
If you read this chapter, you'll find out that you're making the following mistakes:
You are using PdfReader/PdfWriter to add content to an existing document instead of PdfReader/PdfStamper. If you want a nice watermark example, take a look at the ManipulatePdf method in the StampStationery.cs example. Replace background.addTemplate() with background.addImage() to add an image instead of a background page taken from another PDF. You'll also learn more about using an image as a watermark here: How to add a watermark to a PDF file?
You are using PdfReader/PdfWriter to concatenate existing documents instead of PdfCopy. By doing so, you risk all kinds of problems: e.g. parts of pages being cut off, links being removed, annotations getting lost,... Please read my answer to this question: How to merge documents correctly?
You are ignoring the fact that PdfImportedPage is read-only. You can only add content in the context of PdfCopy after creating a PageStamp object. Please take a look at the ConcatenateStamp.cs example.
Summarized: your question is more or less a duplicate of (a combination of) other questions answered before on StackOverflow. It seems that you copy/pasted some code from a source that isn't one of the official sources of documentation.
I am required to replace a word with a new word, selected from a drop-down list by user, in a PDF document in ASP.NET. I am using iTextSharp , but the new PDF that is created is all distorted as I am not able to extract the formatting/styling info of the PDF while extracting. Also, IS There a way to read a pdf line-by-line? Please help..
protected void Page_Load(object sender, EventArgs e)
{
String s = DropDownList1.SelectedValue;
Response.Write(s);
ListFieldNames(s);
}
private void CreatePDF(string text)
{
string outFileName = #"z:\TEMP\PDF\Test_abc.pdf";
Document doc = new Document();
doc.SetMargins(30f, 30f, 30f, 30f);
PdfWriter.GetInstance(doc, new FileStream(outFileName, FileMode.Create));
doc.Open();
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false);
Font times = new Font(bfTimes, 12, Font.BOLDITALIC);
//Chunk ch = new Chunk(text,times);
Paragraph para = new Paragraph(text,times);
//para.SpacingAfter = 9f;
para.Alignment = Element.ALIGN_CENTER;
//para.IndentationLeft = 100;
doc.Add(para);
//doc.Add(new Paragraph(text,times));
doc.Close();
Response.Redirect(#"z:\TEMP\PDF\Test_abc.pdf",false);
}
private void ListFieldNames(string s)
{
ArrayList arrCheck = new ArrayList();
try
{
string pdfTemplate = #"z:\TEMP\PDF\abc.pdf";
//string dest = #"z:\TEMP\PDF\Test_abc.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
string pdfText = string.Empty;
string extracttext = "";
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
PdfReader reader = new PdfReader((string)pdfTemplate);
extracttext = PdfTextExtractor.GetTextFromPage(reader, page, its);
extracttext = Encoding.Unicode.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.Unicode, Encoding.Default.GetBytes(extracttext)));
pdfText = pdfText + extracttext;
pdfText = pdfText.Replace("[xyz]", s);
pdfReader.Close();
}
CreatePDF(pdfText);
}
catch (Exception ex)
{
}
finally
{
}
}
You are making one wrong assumption after the other.
You assume that the concept of "lines" exists in PDF. This is wrong. In Text State, different snippets of text are drawn on the page at absolute positions. For every "show text" operator, iText will return a TextRenderInfo object with the portion of text that was drawn and its coordinates. One line can consist of multiple text snippets. A text snippet may contain whitespace or may even be empty.
You assume that all text in a PDF keeps its natural reading order. This should be true for PDF/UA (UA stands for Universal Accessibility), but it's certainly not true for most PDFs you can find in the wild. That's why iText provides location-based text extraction (see p521 of iText in Action, Second Edition). As explained on p516, the text "Hello World" can be stored in the PDF as "ld", "Wor", "llo", "He". The LocationTextExtractionStrategy will order all the text snippets, reconstructing words if necessary. For instance: it will concatenate "He" and "llo" to "Hello", because there's not sufficient space between the "He" snippet and the "llo" snippet. However, for reasons unknown (probably ignorance), you're using the SimpleTextExtractionStrategy which doesn't order the text based on its location.
You are completely ignoring all the Graphics State operators, as well as the Text State operators that define the font, etc...
You assume that PDF is a Word processing format. This is wrong on many levels, as is your code. Please read the intro of chapter 6 of my book.
All these wrong assumptions almost make me want to vote down your question. At the risk of being voted down myself for this answer, I must tell you that you shouldn't try to "do the same". You're asking something that is very complex, and in many cases even impossible!