/**
* Creates a file specification with the file embedded. The file may
* come from the file system or from a byte array.
* @param writer the <CODE>PdfWriter</CODE>
* @param filePath the file path
* @param fileDisplay the file information that is presented to the user
* @param fileStore the byte array with the file. If it is not <CODE>null</CODE>
* it takes precedence over <CODE>filePath</CODE>
* @param mimeType the optional mimeType
* @param fileParameter the optional extra file parameters such as the creation or modification date
* @param compressionLevel the level of compression
* @throws IOException on error
* @return the file specification
* @since 2.1.3
*/
public static PdfFileSpecification FileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte[] fileStore, String mimeType, PdfDictionary fileParameter, int compressionLevel) {
PdfFileSpecification fs = new PdfFileSpecification();
fs.writer = writer;
fs.Put(PdfName.F, new PdfString(fileDisplay));
fs.SetUnicodeFileName(fileDisplay, false);
PdfEFStream stream;
Stream inp = null;
PdfIndirectReference refi;
PdfIndirectReference refFileLength = null;
try {
if (fileStore == null) {
refFileLength = writer.PdfIndirectReference;
if (File.Exists(filePath)) {
inp = new FileStream(filePath, FileMode.Open, FileAccess.Read);
}
else {
if (filePath.StartsWith("file:/") || filePath.StartsWith("http://") || filePath.StartsWith("https://")) {
WebRequest wr = WebRequest.Create(filePath);
wr.Credentials = CredentialCache.DefaultCredentials;
inp = wr.GetResponse().GetResponseStream();
}
else {
inp = StreamUtil.GetResourceStream(filePath);
if (inp == null)
throw new IOException(MessageLocalization.GetComposedMessage("1.not.found.as.file.or.resource", filePath));
}
}
stream = new PdfEFStream(inp, writer);
}
else
stream = new PdfEFStream(fileStore);
stream.Put(PdfName.TYPE, PdfName.EMBEDDEDFILE);
stream.FlateCompress(compressionLevel);
PdfDictionary param = new PdfDictionary();
if (fileParameter != null)
param.Merge(fileParameter);
if (!param.Contains(PdfName.MODDATE)) {
param.Put(PdfName.MODDATE, new PdfDate());
}
if (fileStore != null) {
param.Put(PdfName.SIZE, new PdfNumber(stream.RawLength));
stream.Put(PdfName.PARAMS, param);
}
else {
stream.Put(PdfName.PARAMS, refFileLength);
}
if (mimeType != null)
stream.Put(PdfName.SUBTYPE, new PdfName(mimeType));
refi = writer.AddToBody(stream).IndirectReference;
if (fileStore == null) {
stream.WriteLength();
param.Put(PdfName.SIZE, new PdfNumber(stream.RawLength));
writer.AddToBody(param, refFileLength);
}
}
finally {
if (inp != null)
try{inp.Close();}catch{}
}
PdfDictionary f = new PdfDictionary();
f.Put(PdfName.F, refi);
f.Put(PdfName.UF, refi);
fs.Put(PdfName.EF, f);
return fs;
}