Hi Team,
I am using CGPDFPage and CGContext to convert the PDF to an image. It is working fine in all circumstances but fails in one circumstance where the size of the PDF is above 50 MB and when the application is made to be on background and again opened. It is also occurring only on physical devices; emulators are working fine. We are using the following code for this conversation:
fileStream.CopyTo(memoryStream);
CGDataProvider provider = new CGDataProvider(memoryStream.ToArray());
CGPDFDocument cGPDFDocument = null;
image = null;
cGPDFDocument = new CGPDFDocument(provider);
using(CGPDFPage pdfPage = cGPDFDocument?.GetPage(1))
{
if (pdfPage != null)
{
CGRect rect = pdfPage.GetBoxRect(CGPDFBox.Media);
if (pdfPage.RotationAngle == 90 || pdfPage.RotationAngle == 270)
{
rect = new CGRect(rect.X, rect.Y, rect.Height, rect.Width);
}
nfloat factor = (nfloat)0.5;
CGRect bounds = new CGRect(rect.X * factor, rect.Y * factor, rect.Width * factor, rect.Height * factor);
UIGraphics.BeginImageContext(bounds.Size);
CGContext context = UIGraphics.GetCurrentContext();
context.SetFillColor(1.0f, 1.0f, 1.0f, 1.0f);
context.FillRect(bounds);
context.TranslateCTM(0, bounds.Height);
context.ScaleCTM(factor, -factor);
context.ConcatCTM(pdfPage.GetDrawingTransform(CGPDFBox.Crop, rect, 0, true));
context.SetRenderingIntent(CGColorRenderingIntent.Default);
context.InterpolationQuality = CGInterpolationQuality.Default;
context.DrawPDFPage(pdfPage);
image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
imageView.Image = image;
parentView.AddSubview(imageView);
}
}
We have added a simple application created on Xamarin.iOS platform that replicates this issue in Assets we have added the PDF with this issue https://www.syncfusion.com/downloads/support/directtrac/general/ze/PdfToImageSample-556012354
We have recorded this for the reference, https://www.syncfusion.com/downloads/support/directtrac/general/ze/CrashBGImgRec-1376481150
This issue is constantly occurring on the "context.DrawPDFPage(pdfPage);" line in my application. On the provided sample, this issue is occurring consistently when the break point is placed on the "context.DrawPDFPage(pdfPage);" line. It also occurs randomly without placing the breakpoint.
We are invoking this function on DidEnterBackground override method of AppDelegate
Do we need to set any to properly retrieve the image from CGPDFPage and add them into context?
PDFKit
RSS for tagDisplay and manipulate PDF documents in your applications using PDFKit.
Posts under PDFKit tag
71 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
How to
Hide the UIMenuController pop-up in PDFKit.
Customize the UIMenuItem in the UIMenuController
After updating iPhone from 17.4 to 17.5.1 UIPrintPageRenderer completely hangs app when getting NumberOfPages from Renderer.
var render = new UIPrintPageRenderer();
if (webViewPages != null && reportIndex < webViewPages.Length)
{
render.AddPrintFormatter(
webViewPages[reportIndex].ViewPrintFormatter,
0);
}
else
{
render.AddPrintFormatter(
new UIMarkupTextPrintFormatter(reportContent),
0);
}
var printable = CoreGraphics.CGRectExtensions.Inset(page, 0, 0);
render.SetValueForKey(NSValue.FromCGRect(page), new NSString("paperRect"));
render.SetValueForKey(NSValue.FromCGRect(printable), new NSString("printableRect"));
var pdfData = new NSMutableData();
UIGraphics.BeginPDFContext(pdfData, page, null);
int pageNum = 0;
for (pageNum = 0; pageNum < render.NumberOfPages; pageNum++)
{
UIGraphics.BeginPDFPage();
var bounds = UIGraphics.PDFContextBounds;
render.DrawPage(pageNum, bounds);
}
UIGraphics.EndPDFContext();
I can render text from TextKit2 into a PDF everything is fine.
But in this case the font is embedded into the PDF.
I need the Pdf to contains only the paths / glyphs and not font.
I can't find a solution yet. I don't want to create an image or using UIViews etc.
It would be nice to get the bezier path of the text
I have done this with TextKit1 but the glyphs are gone with TextKit2
Can anyone help me ?
Thanks :)
Hi,
I need export pdf file to xml file across my app for macos. how i can do it?
I'm stuck on a problem where I need to be able to have the same editing capabilities as in .quickLookPreview and be able to save the edited file to the application with the "Done" button.
So, in nutshell, I need to implement the same functionality many other applications provide including Apple's Files.
However with .quickLookPreview I don't get the ability to save edited files directly to the application, and I've had no luck finding help from the internet (thus this question).
Perhaps somebody has implemented this before and could give me a lead somewhere?
PS. I'm trying to find a solution without any third party libraries
We are experiencing a crash when selecting text in a PDF and moving the cursor over a QR code. This happens when the QR code at the end of the PDF file with no text following it. [Only on iOS 18]
Steps to Reproduce:
Clone the repository:
git clone https://github.com/aliakhtar49/ios18-pdf-crash/tree/main
cd ios18-pdf-crash
Run the application to load the provided PDF
Select some text and move the cursor over the QR code several times
Observe the crash. You can see the gif in the repo
Expected Behavior: The application should not crash
Actual Behavior: The application crashes:
Environment:
iOS version: 18.0
Device: iPhone 15 Pro, iPhone 12 Pro Max
Additional Context:
This issue occurs when the QR code is at the end of the PDF file with no text following it
StackTrace
`thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x19f3e6ec0)
* frame #0: 0x000000019f3e6ec0 CoreGraphics`void PageLayout::ConvertTextRangesToStringRanges<std::__1::span<CFRange, 18446744073709551615ul>, std::__1::back_insert_iterator<std::__1::vector<CFRange, std::__1::allocator<CFRange>>>>(std::__1::span<CFRange, 18446744073709551615ul>&&, std::__1::back_insert_iterator<std::__1::vector<CFRange, std::__1::allocator<CFRange>>>&&) const + 664
frame #1: 0x000000019f424c5c CoreGraphics`CGPDFPageLayoutGetStringRangeIndexNearestPoint + 100
frame #2: 0x000000022b4c096c PDFKit`-[PDFPage characterIndexNearestPoint:] + 128
frame #3: 0x000000022b450950 PDFKit`-[PDFTextInputView _closestPositionToPoint:withinRange:] + 420
frame #4: 0x00000001a0bd02f0 UIKitCore`-[UITextSelectionInteraction _hasTextAlternativesAtLocation:] + 120
frame #5: 0x00000001a03e3834 UIKitCore`-[_UIRemoteKeyboardsEventObserver _hasTextAlternativesForTouch:] + 256
frame #6: 0x000000019fa4e0f8 UIKitCore`-[_UIRemoteKeyboardsEventObserver _endTrackingForTouch:] + 212
frame #7: 0x000000019fa4ca38 UIKitCore`-[_UIRemoteKeyboardsEventObserver _trackTouch:] + 132
frame #8: 0x000000019fa4c94c UIKitCore`-[_UIRemoteKeyboardsEventObserver peekApplicationEvent:] + 220
frame #9: 0x000000019fa4c304 UIKitCore`-[_UIRemoteKeyboards peekApplicationEvent:] + 84
frame #10: 0x000000019fa35dc4 UIKitCore`__dispatchPreprocessedEventFromEventQueue + 4180
frame #11: 0x000000019fa3ef7c UIKitCore`__processEventQueue + 5696
frame #12: 0x000000019f936df4 UIKitCore`updateCycleEntry + 160
frame #13: 0x000000019f934d28 UIKitCore`_UIUpdateSequenceRun + 84
frame #14: 0x000000019f934978 UIKitCore`schedulerStepScheduledMainSection + 172
frame #15: 0x000000019f93580c UIKitCore`runloopSourceCallback + 92
frame #16: 0x000000019d126f9c CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
frame #17: 0x000000019d126f30 CoreFoundation`__CFRunLoopDoSource0 + 176
frame #18: 0x000000019d124a08 CoreFoundation`__CFRunLoopDoSources0 + 244
frame #19: 0x000000019d123c14 CoreFoundation`__CFRunLoopRun + 856
frame #20: 0x000000019d123424 CoreFoundation`CFRunLoopRunSpecific + 608
frame #21: 0x00000001e93211c4 GraphicsServices`GSEventRunModal + 164
frame #22: 0x000000019fc6a130 UIKitCore`-[UIApplication _run] + 816
frame #23: 0x000000019fd1855c UIKitCore`UIApplicationMain + 340
frame #24: 0x0000000105e77c38 MyApp.debug.dylib`main at HSAppDelegate.swift:19:20
frame #25: 0x00000001c3058a74 dyld`start + 2724`
Why does PDFKit delete signature widgets that have already been digitally signed?
This should not happen.
Is there an undocumented flag that needs to be set so that PDFKit doesn't remove them when loading or saving the PDF?
It's difficult to tell if it is happening at
PDFDocument(url: fileURL)
or
document.write(to: outputURL)
If a document is signed and still allows annotations, form filling, comments, etc. we should be able to load the PDF into a PDFDocument and save it without losing the certs.
Instead the certs are gone and only the signature annotation widgets are present.
Here is a simple example of loading and then saving the PDF with out any changes and it shows that the data is actually being changed...
...
import UIKit
import PDFKit
class ViewController: UIViewController {
var pdfView: PDFView!
@IBOutlet weak var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
pdfView = PDFView(frame: self.view.bounds)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(pdfView)
self.view.bringSubviewToFront(myButton)
// Load and compare the PDF data
if let originalData = loadPDF() {
if let loadedData = getRawDataFromLoadedPDF() {
let isDataEqual = comparePDFData(originalData, loadedData)
print("Is original data equal to loaded data? \(isDataEqual)")
}
}
}
@IBAction func onSave(_ sender: Any) {
if let savedData = savePDF() {
if let originalData = loadPDF() {
let isDataEqual = comparePDFData(originalData, savedData)
print("Is original data equal to saved data? \(isDataEqual)")
}
}
}
func loadPDF() -> Data? {
guard let fileURL = Bundle.main.url(forResource: "document", withExtension: "pdf") else {
print("Error: document.pdf not found in bundle.")
return nil
}
do {
let originalData = try Data(contentsOf: fileURL)
if let document = PDFDocument(url: fileURL) {
pdfView.document = document
print("PDF loaded successfully.")
return originalData
} else {
print("Error: Unable to load PDF document.")
return nil
}
} catch {
print("Error reading PDF data: \(error)")
return nil
}
}
func getRawDataFromLoadedPDF() -> Data? {
guard let document = pdfView.document else {
print("Error: No document is currently loaded in pdfView.")
return nil
}
if let data = document.dataRepresentation() {
return data
} else {
print("Error: Unable to get raw data from loaded PDF document.")
return nil
}
}
func comparePDFData(_ data1: Data, _ data2: Data) -> Bool {
return data1 == data2
}
func savePDF() -> Data? {
guard let document = pdfView.document else {
print("Error: No document is currently loaded in pdfView.")
return nil
}
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
guard let documentsURL = urls.first else {
print("Error: Could not find the documents directory.")
return nil
}
let outputURL = documentsURL.appendingPathComponent("document_out.pdf")
if document.write(to: outputURL) {
print("PDF saved successfully to \(outputURL.path)")
do {
let savedData = try Data(contentsOf: outputURL)
return savedData
} catch {
print("Error reading saved PDF data: \(error)")
return nil
}
} else {
print("Error: Unable to save PDF document.")
return nil
}
}
}
We are building our own Cocoapod file. We have to convert a local DOC file to PDF without any server interaction. It will be in offline mode.
Any suggestion will be appreciated.
We have to convert a local DOC file to PDF without any server interaction. It will be in offline mode.
Any suggestion will be appreciated.
Does anyone know why the following call fails?
CGPDFOperatorTableSetCallback(operatorTable, "ID", &callback);
The PDF specification seems to indicate that ID is an operator?
BTW what is the proper topic/subtopic for questions about Quartz? Wasn't sure what topic on the new forums to post this under.