У меня возникла проблема при использовании Syncfusion PDF Viewer с PDF-файлами после внесения изменений с помощью инструмента Draw Ink или любых других инструментов:
Я открыл PDF-файл с помощью PDF Viewer.
Я добавил текст с помощью инструмента Draw Ink .
Затем я загрузил измененный файл, и все появилось правильно, включая добавленный мной текст.
Однако, открыв файл на следующий день с помощью Просмотр PDF, я заметил, что подпись больше не отображается в Просмотр PDF, хотя она существует в файле, если его открыть с помощью другой программы чтения PDF.
Это кажется, существует проблема с тем, как подписи или дополнения к инструменту рисования отображаются или сохраняются после повторного открытия файла в средстве просмотра PDF.
Could you please advise if there is a solution for this issue or a way to ensure that signatures are permanently visible in PDF Viewer?
[HttpPost("Load")]
[IgnoreAntiforgeryToken]
public async Task Load()
{
Console.WriteLine("Load called");
string body;
using (var r = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false))
body = await r.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(body))
return BadRequest("Empty body");
var json = JsonConvert.DeserializeObject(body)
?? new Dictionary(StringComparer.OrdinalIgnoreCase);
if (!json.TryGetValue("document", out var doc) || string.IsNullOrWhiteSpace(doc))
return BadRequest("Missing 'document'");
// build data object from incoming json (preserve incoming hashId if present)
var data = new Dictionary(json, StringComparer.OrdinalIgnoreCase);
// If client passed hashId and we have cached annotation data, attach it
if (data.TryGetValue("hashId", out var incomingHash) && !string.IsNullOrWhiteSpace(incomingHash))
{
if (_cache.TryGetValue($"pdf:ann:{incomingHash}", out string annBase64) && !string.IsNullOrWhiteSpace(annBase64))
{
data["importedData"] = annBase64;
data["annotationDataFormat"] = "Json";
Console.WriteLine($"Load: attached importedData for hashId={incomingHash} (len={annBase64.Length})");
}
else
{
Console.WriteLine($"Load: no cached annotations for hashId={incomingHash}");
}
}
byte[] bytes;
if (IsHttpUrl(doc))
{
var bust = doc.Contains("?") ? "&" : "?";
var noCacheUrl = doc + bust + "v=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
using var http = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All });
http.DefaultRequestHeaders.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MaxAge = TimeSpan.Zero
};
bytes = await http.GetByteArrayAsync(noCacheUrl);
if (bytes == null || bytes.Length == 0)
return BadRequest("Remote document returned empty content.");
}
else if (IsDataUrl(doc))
{
var comma = doc.IndexOf(',');
if (comma < 0) return BadRequest("Invalid data URL.");
var b64 = doc[(comma + 1)..];
bytes = Convert.FromBase64String((b64));
}
else if (LooksLikeBase64(doc))
{
bytes = Convert.FromBase64String((doc));
}
else
{
var localPath = Path.IsPathRooted(doc)
? doc
: Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "wwwroot", "Data", doc));
if (!System.IO.File.Exists(localPath))
return NotFound($"File not found: {localPath}");
bytes = await System.IO.File.ReadAllBytesAsync(localPath);
if (!data.ContainsKey("fileName"))
data["fileName"] = Path.GetFileName(localPath);
}
var pdfviewer = new PdfRenderer(_cache);
object jsonResult;
var stream = new MemoryStream(bytes);
jsonResult = pdfviewer.Load(stream, data);
Console.WriteLine("Load jsonResult: " + JsonConvert.SerializeObject(jsonResult));
return Content(JsonConvert.SerializeObject(jsonResult), "application/json; charset=utf-8");
}
У меня возникла проблема при использовании [b]Syncfusion PDF Viewer[/b] с PDF-файлами после внесения изменений с помощью инструмента Draw Ink или любых других инструментов: [list] [*]Я открыл PDF-файл с помощью [b]PDF Viewer[/b].
[*]Я добавил текст с помощью инструмента [b]Draw Ink[/b] .
[*]Затем я загрузил измененный файл, и все появилось правильно, включая добавленный мной текст.
[*]Однако, открыв файл на следующий день с помощью [b]Просмотр PDF[/b], я заметил, что подпись больше не отображается в [b]Просмотр PDF[/b], хотя она существует в файле, если его открыть с помощью другой программы чтения PDF.
[/list] Это кажется, существует проблема с тем, как подписи или дополнения к инструменту рисования отображаются или сохраняются после повторного открытия файла в [b]средстве просмотра PDF[/b]. [code]Could you please advise if there is a solution for this issue or a way to ensure that signatures are permanently visible in PDF Viewer?
[HttpPost("Load")] [IgnoreAntiforgeryToken] public async Task Load() { Console.WriteLine("Load called");
string body; using (var r = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false)) body = await r.ReadToEndAsync();
if (string.IsNullOrWhiteSpace(body)) return BadRequest("Empty body");
var json = JsonConvert.DeserializeObject(body) ?? new Dictionary(StringComparer.OrdinalIgnoreCase);
if (!json.TryGetValue("document", out var doc) || string.IsNullOrWhiteSpace(doc)) return BadRequest("Missing 'document'");
// build data object from incoming json (preserve incoming hashId if present) var data = new Dictionary(json, StringComparer.OrdinalIgnoreCase);
// If client passed hashId and we have cached annotation data, attach it if (data.TryGetValue("hashId", out var incomingHash) && !string.IsNullOrWhiteSpace(incomingHash)) { if (_cache.TryGetValue($"pdf:ann:{incomingHash}", out string annBase64) && !string.IsNullOrWhiteSpace(annBase64)) { data["importedData"] = annBase64; data["annotationDataFormat"] = "Json"; Console.WriteLine($"Load: attached importedData for hashId={incomingHash} (len={annBase64.Length})"); } else { Console.WriteLine($"Load: no cached annotations for hashId={incomingHash}"); } }
byte[] bytes; if (IsHttpUrl(doc)) { var bust = doc.Contains("?") ? "&" : "?"; var noCacheUrl = doc + bust + "v=" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
using var http = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All }); http.DefaultRequestHeaders.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue { NoCache = true, NoStore = true, MaxAge = TimeSpan.Zero };
bytes = await http.GetByteArrayAsync(noCacheUrl); if (bytes == null || bytes.Length == 0) return BadRequest("Remote document returned empty content."); } else if (IsDataUrl(doc)) { var comma = doc.IndexOf(','); if (comma < 0) return BadRequest("Invalid data URL."); var b64 = doc[(comma + 1)..]; bytes = Convert.FromBase64String((b64)); } else if (LooksLikeBase64(doc)) { bytes = Convert.FromBase64String((doc)); } else { var localPath = Path.IsPathRooted(doc) ? doc : Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "wwwroot", "Data", doc)); if (!System.IO.File.Exists(localPath)) return NotFound($"File not found: {localPath}"); bytes = await System.IO.File.ReadAllBytesAsync(localPath); if (!data.ContainsKey("fileName")) data["fileName"] = Path.GetFileName(localPath); }
var pdfviewer = new PdfRenderer(_cache); object jsonResult;
var stream = new MemoryStream(bytes); jsonResult = pdfviewer.Load(stream, data);
var currentPdfName = ''; var currentHashId = null; var currentPdfLink = '';
function initializePdfViewer() { try { console.log('initializePdfViewer: start');
if (typeof ej === 'undefined' || !ej.pdfviewer || !ej.base) { throw new Error('Syncfusion EJ2 scripts not loaded (ej is undefined). Ensure scripts are included before this file.'); } if (typeof syncfusion_key === 'undefined') { console.warn('initializePdfViewer: syncfusion_key is undefined — registerLicense may fail'); } else { try { ej.base.registerLicense(syncfusion_key); } catch (e) { console.warn('registerLicense failed', e); } }
const el = document.querySelector('#pdfViewer'); if (!el) { throw new Error('Missing DOM element with id="pdfViewer". Create in your page.'); }
function getFileNameFromUrl(url, fallback = 'document.pdf') { if (!url) return fallback; currentPdfLink = url; const clean = url.split('#')[0].split('?')[0]; let name = clean.split('/').pop(); if (!name) return fallback; name = decodeURIComponent(name); return name || fallback; }
if ((uploadRes?.data && uploadRes.data.includes('OK')) || uploadRes?.isSussccful === true) { $('#PdfPreviewButtonModal').click(); displaySuccessfulAlert('تم حفظ الـ PDF بكل التعديلات (يشمل الـ Ink).'); } else { displayErrorAlert(uploadRes?.message || 'حدث خطأ أثناء الحفظ'); }