I want to print two Jfree charts in the same document using iTextPdf, when I tried using this code, the following JFreeChart overwrite the previous one. As a result I got the second chart on both of two pages of the pdf.
public void ExportChart(OutputStream out, int width, int height) throws IOException, DocumentException {
Rectangle rect = new com.itextpdf.text.Rectangle((float) width, (float) height+130);
Document document = new com.itextpdf.text.Document(rect);
PdfWriter writer = null;
writer=PdfWriter.getInstance(document, out);
document.open();
document.add(addHeaderInfo(width));
DefaultFontMapper mapper = new DefaultFontMapper();
FontFactory.registerDirectories();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2d = tp.createGraphics(width, height, mapper);
tp.setWidth(width);
tp.setHeight(height);
//barStat is a JFreeChart Objecct
barStat.draw(g2d, new java.awt.Rectangle(width, height));
cb.addTemplate(tp, 0, 0);
document.newPage();
SingleHistogramDialog singleHD=new SingleHistogramDialog();
JFreeChart barStat2=singleHD.Histogram();
document.add(addHeaderInfo(width));
FontFactory.registerDirectories();
tp.setWidth(width);
tp.setHeight(height);
barStat2.draw(g2d, new java.awt.Rectangle(width, height));
g2d.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
I copied your code literally, and I made a couple of changes:
public void ExportChart(OutputStream out, int width, int height) throws IOException, DocumentException {
Rectangle rect = new com.itextpdf.text.Rectangle((float) width, (float) height+130);
Document document = new com.itextpdf.text.Document(rect);
PdfWriter writer = null;
writer=PdfWriter.getInstance(document, out);
document.open();
document.add(addHeaderInfo(width));
DefaultFontMapper mapper = new DefaultFontMapper();
FontFactory.registerDirectories();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2d = tp.createGraphics(width, height, mapper);
//barStat is a JFreeChart Objecct
barStat.draw(g2d, new java.awt.Rectangle(width, height));
cb.addTemplate(tp, 0, 0);
document.newPage();
SingleHistogramDialog singleHD=new SingleHistogramDialog();
JFreeChart barStat2=singleHD.Histogram();
document.add(addHeaderInfo(width));
tp = cb.createTemplate(width, height);
g2d = tp.createGraphics(width, height, mapper);
barStat2.draw(g2d, new java.awt.Rectangle(width, height));
g2d.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
I solved my problem by changing my above code this way
public void ExportChart(OutputStream out, int width, int height) throws
IOException, DocumentException {
Rectangle rect = new com.itextpdf.text.Rectangle((float) width, (float)
height+130);
Document document = new com.itextpdf.text.Document(rect);
PdfWriter writer = null;
writer=PdfWriter.getInstance(document, out);
document.open();
document.add(addHeaderInfo(width));
DefaultFontMapper mapper = new DefaultFontMapper();
FontFactory.registerDirectories();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2d = tp.createGraphics(width, height, mapper);
tp.setWidth(width);
tp.setHeight(height);
barStat.draw(g2d, new java.awt.Rectangle(width, height));
Histogram singleHD=new Histogram();
JFreeChart barStat2=singleHD.Histogram();
PdfTemplate tp2 = cb.createTemplate(width, height);
Graphics2D g2d2 = tp2.createGraphics(width, height, mapper);
tp2.setWidth(width);
tp2.setHeight(height);
barStat2.draw(g2d2, new java.awt.Rectangle(width, height));
g2d.dispose();
cb.addTemplate(tp, 0, 0);
document.newPage();
document.add(addHeaderInfo(width));
g2d2.dispose();
cb.addTemplate(tp2, 0, 0);
document.close();
}
Related
im trying to sign a document several times simulating a signature by different users using itext 5.5.13.1, PdfStamper is on AppendMode. If document has not signatures, the certification level is CERTIFIED_NO_CHANGES_ALLOWED or CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, else i dont set this param for PdfSignatureAppearence. After the second signing the first signature is invalid, because the document was changed. Any ideas how to fix this?
Here's my code:
public void Sign(string Thumbprint, string document, string logoPath) {
X509Certificate2 certificate = FindCertificate(Thumbprint);
PdfReader reader = new PdfReader(document);
//Append mode
PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(SignedDocumentPath(document), FileMode.Create, FileAccess.Write), '\0', null, true);
int signatureWidth = 250;
int signatureHeight = 100;
int NewXPos = 0;
int NewYPos = 0;
SetStampCoordinates(reader, st, ref NewXPos, ref NewYPos, signatureWidth, signatureHeight);
PdfSignatureAppearance sap = st.SignatureAppearance;
if (reader.AcroFields.GetSignatureNames().Count == 0)
{
SetSignatureFieldOptions(certificate, sap, reader, "1", 1, NewXPos, NewYPos, signatureWidth, signatureHeight);
}
else {
SetSignatureFieldOptions(certificate, sap, reader, "2", NewXPos, NewYPos, signatureWidth, signatureHeight);
}
Image image = Image.GetInstance(logoPath);
image.ScaleAbsolute(50, 50);
Font font1 = SetFont("TIMES.TTF", BaseColor.BLUE, 10, 0);
Font font2 = SetFont("TIMES.TTF", BaseColor.BLUE, 8, 0);
PdfTemplate layer = sap.GetLayer(2);
Chunk chunk1 = new Chunk($"\r\nДОКУМЕНТ ПОДПИСАН\r\nЭЛЕКТРОННОЙ ПОДПИСЬЮ\r\n", font1);
Chunk chunk2 = new Chunk($"Сертификат {certificate.Thumbprint}\r\n" +
$"Владелец {certificate.GetNameInfo(X509NameType.SimpleName, false)}\r\n" +
$"Действителен с {Convert.ToDateTime(certificate.GetEffectiveDateString()).Date.ToShortDateString()} " +
$"по {Convert.ToDateTime(certificate.GetExpirationDateString()).Date.ToShortDateString()}\r\n", font2);
PdfTemplate layer0 = sap.GetLayer(0);
image.SetAbsolutePosition(5, 50);
layer0.AddImage(image);
Paragraph para1 = SetParagraphOptions(chunk1, 1, 50, 0, 2, 1.1f);
Paragraph para2 = SetParagraphOptions(chunk2, 0, 5, 15, 0.5f, 1.1f);
ColumnText ct = new ColumnText(layer);
ct.SetSimpleColumn(3f, 3f, layer.BoundingBox.Width - 3f, layer.BoundingBox.Height);
ct.AddElement(para1);
ct.AddElement(para2);
ct.Go();
layer.SetLineWidth(3);
layer.SetRGBColorStroke(0, 0, 255);
layer.Rectangle(0, 0, layer.BoundingBox.Right, layer.BoundingBox.Top);
layer.Stroke();
EncryptDocument(certificate, sap);
}
public X509Certificate2 FindCertificate(string Thumbprint) {
X509Store store = new X509Store("My", StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
X509Certificate2Collection found = store.Certificates.Find(
X509FindType.FindByThumbprint, Thumbprint, true);
X509Certificate2 certificate = found[0];
if (certificate.PrivateKey is Gost3410_2012_256CryptoServiceProvider cert_key)
{
var cspParameters = new CspParameters
{
KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName,
ProviderType = cert_key.CspKeyContainerInfo.ProviderType,
ProviderName = cert_key.CspKeyContainerInfo.ProviderName,
Flags = cert_key.CspKeyContainerInfo.MachineKeyStore
? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
: (CspProviderFlags.UseExistingKey),
KeyPassword = new SecureString()
};
certificate = new X509Certificate2(certificate.RawData)
{
PrivateKey = new Gost3410_2012_256CryptoServiceProvider(cspParameters)
};
}
return certificate;
}
public Font SetFont(string TTFFontName, BaseColor color, float size, int style) {
string ttf = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), TTFFontName);
BaseFont baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont, size, style);
font.Color = color;
return font;
}
public Paragraph SetParagraphOptions(Chunk chunk, int ParagraphAligment, float marginLeft, float marginTop, float fixedLeading, float multipledLeading) {
Paragraph paragraph = new Paragraph();
paragraph.Alignment = ParagraphAligment;
paragraph.IndentationLeft = marginLeft;
paragraph.SpacingBefore = marginTop;
paragraph.SetLeading(fixedLeading, multipledLeading);
paragraph.Add(chunk);
return paragraph;
}
public string SignedDocumentPath(string document) {
string filename = String.Concat(Path.GetFileNameWithoutExtension(document), "_signed.pdf");
string path = Path.Combine(Path.GetDirectoryName(document), filename);
return path;
}
public void SetSignatureFieldOptions(X509Certificate2 certificate, PdfSignatureAppearance sap, PdfReader reader, string field, int level, int XPos, int YPos, int width, int height)
{
X509CertificateParser parser = new X509CertificateParser();
try
{
Rectangle rectangle = new Rectangle(XPos, YPos, XPos + width, YPos + height);
sap.SetVisibleSignature(rectangle, reader.NumberOfPages, field);
sap.Certificate = parser.ReadCertificate(certificate.RawData);
sap.Reason = "I agree";
sap.Location = "Location";
sap.Acro6Layers = true;
sap.SignDate = DateTime.Now;
sap.CertificationLevel = level;
}
catch (Exception ex)
{
if (ex.Message == $"The field {certificate.Thumbprint} already exists.")
throw new Exception("Вы уже подписали данный документ");
}
}
public void SetSignatureFieldOptions(X509Certificate2 certificate, PdfSignatureAppearance sap, PdfReader reader,string field, int XPos, int YPos, int width, int height) {
X509CertificateParser parser = new X509CertificateParser();
try
{
Rectangle rectangle = new Rectangle(XPos, YPos, XPos + width, YPos + height);
sap.SetVisibleSignature(rectangle, reader.NumberOfPages, field);
sap.Certificate = parser.ReadCertificate(certificate.RawData);
sap.Reason = "I agree";
sap.Location = "Location";
sap.Acro6Layers = true;
sap.SignDate = DateTime.Now;
}
catch (Exception ex) {
if (ex.Message == $"The field {certificate.Thumbprint} already exists.")
throw new Exception("Вы уже подписали данный документ");
}
}
public void EncryptDocument(X509Certificate2 certificate, PdfSignatureAppearance sap) {
PdfName filterName;
if (certificate.PrivateKey is Gost3410CryptoServiceProvider)
filterName = new PdfName("CryptoPro#20PDF");
else
filterName = PdfName.ADOBE_PPKLITE;
PdfSignature dic = new PdfSignature(filterName, PdfName.ADBE_PKCS7_DETACHED);
dic.Date = new PdfDate(sap.SignDate);
dic.Name = certificate.GetNameInfo(X509NameType.SimpleName, false);
if (sap.Reason != null)
dic.Reason = sap.Reason;
if (sap.Location != null)
dic.Location = sap.Location;
sap.CryptoDictionary = dic;
int intCSize = 4000;
Dictionary<PdfName, int> hashtable = new Dictionary<PdfName, int>();
hashtable[PdfName.CONTENTS] = intCSize * 2 + 2;
sap.PreClose(hashtable);
Stream s = sap.GetRangeStream();
MemoryStream ss = new MemoryStream();
int read = 0;
byte[] buff = new byte[8192];
while ((read = s.Read(buff, 0, 8192)) > 0)
{
ss.Write(buff, 0, read);
}
ContentInfo contentInfo = new ContentInfo(ss.ToArray());
SignedCms signedCms = new SignedCms(contentInfo, true);
CmsSigner cmsSigner = new CmsSigner(certificate);
signedCms.ComputeSignature(cmsSigner, false);
byte[] pk = signedCms.Encode();
byte[] outc = new byte[intCSize];
PdfDictionary dic2 = new PdfDictionary();
Array.Copy(pk, 0, outc, 0, pk.Length);
dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
sap.Close(dic2);
}
The Change
The most important part of your screenshot
is the text "1 Page(s) Modified" between the signatures on the signature panel. This tells us that you do other changes than merely adding and filling signature fields. Inspecting the file itself one quickly recognizes the change:
In the original sample.pdf
there is just a single content stream.
In sample_signed.pdf with one signature
there are three content streams, the original one enveloped by the new ones.
In sample_signed_signed.pdf with two signatures
there are five content streams, the former three enveloped by two new ones.
So in each signing pass you change the page content. As you can read in this answer, changes to the page content of signed documents are always disallowed. It doesn't even help that the contents of the added streams are trivial, each stream added in front contains:
q
and each stream added at the end contains
Q
q
Q
i.e. only some saving and restoring the graphics state happens.
The Cause
The changes described above are typical preparation steps done by the PdfStamper method GetOverContent, wrapping the original content in a q ... Q (save & restore graphics state) envelope to prevent changes there to influence additions in the OverContent and starting a new block also enveloped in such an envelope. That the latter block remained empty, indicates that the OverContent has not been edited.
I don't find such a call in the code you posted, but in your code the method SetStampCoordinates is missing. Do you probably call GetOverContent for the PdfStamper argument in that method?
When i generates a PDF file from an existing PDF file with itextsharp,my work code is
The soruce pdf
string sourceFile = "a4.pdf", targetFile = "processed.pdf";
PdfReader reader = new PdfReader(sourceFile);
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(targetFile, FileMode.Create));
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
for (int pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
{
doc.SetPageSize(reader.GetPageSizeWithRotation(pageNumber));
doc.NewPage();
page = writer.GetImportedPage(reader, pageNumber);
//Write a PageIndex
ColumnText.ShowTextAligned(cb, PdfContentByte.ALIGN_CENTER, new Phrase(pageNumber.ToString()), 100, 0, 0);
cb.AddTemplate(page, 0, 0);
}
doc.Close();
The problem is, when i get a PdfImportedPage from reader,page = writer.GetImportedPage(reader, pageNumber); the content in sourceFile's hidden layer will display.The processed.pdf has none layer.
How can i get a PdfImportedPage without hidden layer context use Itextsharp.
I have a problem with a camera, I want to take a screenshot but I get this error:
Flare renderer to update not found UnityEngine.Camera:Render()
c__Iterator4:MoveNext() (at
Assets/Scripts/ActionCam.cs:43)
My code:
public IEnumerator TakeScreenshot() {
yield return new WaitForEndOfFrame();
Camera camOV = _Camera;
RenderTexture currentRT = RenderTexture.active;
RenderTexture.active = camOV.targetTexture;
camOV.Render(); // here is the problem...
Texture2D imageOverview = new Texture2D(camOV.targetTexture.width, camOV.targetTexture.height, TextureFormat.RGB24, false);
imageOverview.ReadPixels(new Rect(0, 0, camOV.targetTexture.width, camOV.targetTexture.height), 0, 0);
imageOverview.Apply();
RenderTexture.active = currentRT;
byte[] bytes = imageOverview.EncodeToPNG();
string path = ScreenShotName(Convert.ToInt32(imageOverview.width), Convert.ToInt32(imageOverview.height));
System.IO.File.WriteAllBytes(path, bytes);
}
There are my camera settings:
If I deactivate the "Flare Layer" I don't get this error, but my screenshots are more or less empty, only the skybox:
any idea?
I Use 3 types of screenshot in unity:
Application.CaptureScreenshot(ScreenSgotFile): Not using anymore because I prefer methods that stores the screenshots in memory. (I don't need the file because it is attached to a MailMessage and sended by an SmtpClient)
OnPostRender (it must be attached to a camera):
void OnPostRender(){
Texture2D ScreenShot=new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
RenderTexture.active=null;
ScreenShot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
ScreenShot.Apply();
byte[] PngData=ScreenShot.EncodeToPNG();
PngStream = new MemoryStream(PngData);
//File.WriteAllBytes(FileShot, PngData);
// Preview on a sprite
Sprite Spr=Sprite.Create(ScreenShot, new Rect(0, 0, ScreenShot.width, ScreenShot.height),Vector2.zero, 100);
Preview.sprite=Spr;
Preview.gameObject.SetActive(true);
}
The same code but at the end of frame:
void Update(){
...
StartCoroutine(ScreenShotAtEndOfFrame());
}
public IEnumerator ScreenShotAtEndOfFrame(){
yield return new WaitForEndOfFrame();
Texture2D ScreenShot=new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
RenderTexture.active=null; `enter code here`
ScreenShot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
ScreenShot.Apply();
byte[] PngData=ScreenShot.EncodeToPNG();
PngStream = new MemoryStream(PngData);
//File.WriteAllBytes(FileShot, PngData);
// Preview on a sprite
Sprite Spr=Sprite.Create(ScreenShot, new Rect(0, 0, ScreenShot.width, ScreenShot.height),Vector2.zero, 100);
Preview.sprite=Spr;
Preview.gameObject.SetActive(true);
}
I have a landscaped form lay on a top half of A4 page, I want it to be rotated and enlarge to a portrait layout size fill up the A4 then saved before it is faxed out. Otherwise, the fax service program will fax it out with only partial info. Here is my attempt, result is the same as the input pdf. This is my first day on programming using iText, all the google not getting me what I want. Please let me know if you can help. Thanks,
public class CopeALandscapePdfFiletoPortraitPdfFile {
//public static final String SRC = "resources/pdfs/landscapeForm.pdf";
public static final String SRC = "resources/pdfs/potraitForm.pdf";
public static final String DEST = "results/stamper/portraitFormAfterCopy.pdf";
public static void main(String[] args) throws IOException, DocumentException
{
copyPdf();
}
private static void copyPdf() throws IOException, DocumentException
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(SRC);
document.newPage();
int n = reader.getNumberOfPages();
PdfDictionary page;
PdfNumber rotate;
for (int p = 1; p <= n; p++) {
page = reader.getPageN(p);
rotate = page.getAsNumber(PdfName.ROTATE);
if (rotate == null) {
page.put(PdfName.ROTATE, new PdfNumber(90));
} else {
page.put(PdfName.ROTATE, new PdfNumber((rotate.intValue() + 90) % 360));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(DEST));
stamper.close();
PdfImportedPage ipage = writer.getImportedPage(stamper.getReader(), 1);
cb.addTemplate(ipage, 0, 0);
document.close();
}
}
As you want to enlarge the PDF anyways, I would put enlarging and rotating into one afine transformation. Thus:
PdfReader reader = new PdfReader(SOURCE);
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, RESULT);
document.open();
double sqrt2 = Math.sqrt(2);
Rectangle pageSize = reader.getPageSize(1);
PdfImportedPage importedPage = writer.getImportedPage(reader, 1);
writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2);
document.close();
(EnlargePagePart.java)
E.g. for this page
it generates
Is it possible to edit width of PdfTemplate object before close of document ?
In my pdf process I create a document, and set a template for write total page number. I set width but it doesnot works :
// onOpenDocument
PdfTemplate pageNumTemplate = writer.getDirectContent().createTemplate(10, 20);
globalDataMap.put("myTemplate", pageNumTemplate)
// onCloseDocument
Font font = (Font) globalDataMap.get("myFont");
String pagenum = String.valueOf(writer.getPageNumber());
float widthPoint = font.getBaseFont().getWidthPoint(pagenum, font.getSize());
PdfTemplate pdfTemplate = (PdfTemplate) globalDataMap.get("myTemplate");
pdfTemplate.setWidth(widthPoint);
ColumnText.showTextAligned(pdfTemplate, Element.ALIGN_LEFT, new Phrase(pagenum), 0, 1, 0);
An error in the OP's initial code
You call ColumnText.showTextAligned with a String as third parameter:
String pagenum = String.valueOf(writer.getPageNumber());
[...]
ColumnText.showTextAligned(pdfTemplate, Element.ALIGN_LEFT, pagenum, 0, 1, 0);
But all ColumnText.showTextAligned overloads expect a Phrase there:
public static void showTextAligned(final PdfContentByte canvas, final int alignment, final Phrase phrase, final float x, final float y, final float rotation)
public static void showTextAligned(final PdfContentByte canvas, int alignment, final Phrase phrase, final float x, final float y, final float rotation, final int runDirection, final int arabicOptions)
(at least up to the current 5.5.9-SNAPSHOT development version).
Thus, you might want to use
ColumnText.showTextAligned(pdfTemplate, Element.ALIGN_LEFT, new Phrase(pagenum), 0, 1, 0);
instead.
But now it works
Based on the OP's code I built this proof-of-concept:
try ( FileOutputStream stream = new FileOutputStream(new File(RESULT_FOLDER, "dynamicTemplateWidths.pdf")) )
{
Document document = new Document(PageSize.A6);
PdfWriter writer = PdfWriter.getInstance(document, stream);
writer.setPageEvent(new PdfPageEventHelper()
{
PdfTemplate dynamicTemplate = null;
Font font = new Font(BaseFont.createFont(), 12);
String postfix = "0123456789";
#Override
public void onOpenDocument(PdfWriter writer, Document document)
{
super.onOpenDocument(writer, document);
dynamicTemplate = writer.getDirectContent().createTemplate(10, 20);
}
#Override
public void onEndPage(PdfWriter writer, Document document)
{
writer.getDirectContent().addTemplate(dynamicTemplate, 100, 300);
}
#Override
public void onCloseDocument(PdfWriter writer, Document document)
{
float widthPoint = font.getBaseFont().getWidthPoint(postfix, font.getSize());
dynamicTemplate.setWidth(widthPoint / 2.0f);
ColumnText.showTextAligned(dynamicTemplate, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber()) + "-" + postfix), 0, 1, 0);
}
});
document.open();
document.add(new Paragraph("PAGE 1"));
document.newPage();
document.add(new Paragraph("PAGE 2"));
document.close();
}
The output:
Considering I set the template width to half the width of the postfix 0123456789 in onCloseDocument, this is exactly as expected.