SwiftUI ScrollView to PDF - pdf

Currently, I am using this code to create a PDF, but it only creates a PDF of the part of the page the user is looking at, and not the entire scroll view. How can I create a multi-page PDF to get the entire scroll view?
func exportToPDF(width:CGFloat, height:CGFloat, airplane: String, completion: #escaping (String) -> Void) {
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let outputFileURL = documentDirectory.appendingPathComponent("smartsheet-\(airplane.afterchar(first: "N")).pdf")
//Normal with
let width: CGFloat = width
//Estimate the height of your view
let height: CGFloat = height
let charts = SmartSheet().environmentObject(Variables())
let pdfVC = UIHostingController(rootView: charts)
pdfVC.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
//Render the view behind all other views
let rootVC = UIApplication.shared.windows.first?.rootViewController
rootVC?.addChild(pdfVC)
rootVC?.view.insertSubview(pdfVC.view, at: 0)
//Render the PDF
let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: width, height: height))
DispatchQueue.main.async {
do {
try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
context.beginPage()
rootVC?.view.layer.render(in: context.cgContext)
})
UserDefaults.standard.set(outputFileURL, forKey: "pdf")
UserDefaults.standard.synchronize()
print("wrote file to: \(outputFileURL.path)")
completion(outputFileURL.path)
} catch {
print("Could not create PDF file: \(error.localizedDescription)")
}
pdfVC.removeFromParent()
pdfVC.view.removeFromSuperview()
}
}

I just posted this answer to another question as well.
https://stackoverflow.com/a/74033480/14076779
After attempting a number of solutions to creating a pdf from a SwiftUI ScrollView and landed on this implementation. It is by no means an implementation that is pretty, but it seems to work.
M use case is that I present a modal to capture a user's signature and when the signature is collected, the content of the current screen is captured. There is no pagination, just a capture of the content currently rendered to the width of the screen and as much length as is required by the view.
The content consists of an array of cards that are dynamically generated, so the view has no awareness of the content and cannot calculate the height. I have not tested on a list, but I imagine it would provide similar results.
struct SummaryTabView: View {
// MARK: View Model
#ObservedObject var viewModel: SummaryTabViewModel
// MARK: States and Bindings
#State private var contentSize: CGSize = .zero // Updated when the size preference key for the overlay changes
#State private var contentSizeForPDF: CGSize = .zero // Set to match the content size when the signature modal is displayed.
// MARK: Initialization
init(viewModel: SummaryTabViewModel) {
self.viewModel = viewModel
}
// MARK: View Body
var body: some View {
ScrollView {
content
.background(Color.gray)
// Placing the a geometry reader in the overlay here seems to work better than doing so in a background and updates the size value for the size preference key.
.overlay(
GeometryReader { proxy in
Color.clear.preference(key: SizePreferenceKey.self,
value: proxy.size)
}
)
}
.onPreferenceChange(SizePreferenceKey.self) {
// This keeps the content size up-to-date during changes to the content including rotating.
contentSize = $0
}
// There are issues with the sizing the content when the orientation changes and a modal view is open such as when collecting the signature. If the iPad is rotated when the modal is open, then the content size is not being set properly. To avoid this, when the user opens the modal for signing, the content size for PDF generation is set to the current value since the signature placeholder is already present so the content size will not change.
.onReceive(NotificationCenter.default.publisher(for: .openingSignatureModal)) { _ in
self.contentSizeForPDF = contentSize
}
}
// MARK: Subviews
var header: SceneHeaderView {
SceneHeaderView(viewModel: viewModel)
}
// Extracting this view into a variable allows grabbing the screenshot when the customer signature is collected.
var content: some View {
LazyVStack(spacing: 16) {
header
ForEach(viewModel.cardViewModels) { cardViewModel in
// Each card needs to be in a VStack with no spacing or it will end up having a gap between the header and the card body.
VStack(spacing: 0) {
UICardView(viewModel: cardViewModel)
}
}
}
.onReceive(viewModel.signaturePublisher) {
saveSnapshot(content: content, size: contentSizeForPDF)
}
}
// MARK: View Functions
/// Creates and saves a pdf data file to the inspection's report property. This is done asynchronously to avoid odd behavior with the graphics renering process.
private func saveSnapshot<Content: View>(content: Content, size: CGSize) {
let pdf = content
.frame(width: size.width, height: size.height)
.padding(.bottom, .standardEdgeSpacing) // Not sure why this padding needs to be added but for some reason without it the pdf is tight to the last card on the bottom. It appears that extra padding is being added above the header, but not sure why.
.toPDF(format: self.pdfFormat)
self.saveReport(data: pdf)
}
private var pdfFormat: UIGraphicsPDFRendererFormat {
let format = UIGraphicsPDFRendererFormat()
// TODO: Add Author here
let metadata = [kCGPDFContextCreator: "Mike",
kCGPDFContextAuthor: viewModel.userService.userFullName]
format.documentInfo = metadata as Dictionary<String, Any>
return format
}
private func saveReport(data: Data?) {
guard let data = data else {
log.error("No data generated for pdf.")
return
}
do {
try viewModel.saveReport(data)
print("Report generated for inspection")
} catch {
print("Failed to create pdf report due to error: \(error)")
}
// Used to verify report in simulator
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
var filename = "\(UUID().uuidString.prefix(6)).pdf"
let bodyPath = documentDirectory.appendingPathComponent(filename)
do {
let value: Data? = viewModel.savedReport
try value?.write(to: bodyPath)
print("pdf directory: \(documentDirectory)")
} catch {
print("report not generated")
}
}
// MARK: Size Preference Key
private struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
}
// MARK: Get image from SwiftUI View
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
func toPDF(format: UIGraphicsPDFRendererFormat) -> Data {
let controller = UIHostingController(rootView: self)
let view = controller.view
let contentSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: contentSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsPDFRenderer(bounds: controller.view.bounds, format: format)
return renderer.pdfData { context in
context.beginPage()
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
I landed on using a size preference key because a lot of other options did not perform as expected. For instance, setting the content size in .onAppear ended up yielding a pdf with a lot of space above and below it. At one point I was creating the pdf using a boolean state that when changed would use the geometry reader's current geometry. That generally worked, but would provide unexpected results when the user would rotate the device while a modal was open.
References (as best I can recall):
SizePreferenceKey: https://swiftwithmajid.com/2020/01/15/the-magic-of-view-preferences-in-swiftui/
Snapshot View extension: https://www.hackingwithswift.com/quick-start/swiftui/how-to-convert-a-swiftui-view-to-an-image

Related

CollectionView using NSDiffableDataSource with UICollectionViewFlowLayout

When I use UICollectionView with UICollectionViewFlowLayout set. And then try to apply snapshots of datasource via
// load initial data
reloadDataSource()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
self.reloadDataSource(animating: true)
}
I am getting crash on second snapshot applied after 3 seconds delay.
The crash is happening only when animating: true
If I set animating to false then there is no crash but the collection view if left empty.
Here is this mathod applying data source
extension CollectionViewController {
func reloadDataSource(animating: Bool = false) {
print("reloading data source with snapshot -> \(snapshot.numberOfItems)")
self.dataSource.apply(self.snapshot, animatingDifferences: animating) {
print("applying snapshot completed!")
}
}
}
Data source is just
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: cellProvider)
Full project you can play (may changes over time): https://github.com/michzio/SwifUICollectionView
Update
I've tried to simplify example and do something like this and it doesn't work correctly. It seems that moving .apply() to background queue, other queue causes empty data in collectionview
func reloadDataSource(animating: Bool = false) {
print("reloading data source with snapshot -> \(snapshot.numberOfItems)")
diffQueue.async {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.categories])
snapshot.appendItems(Item.categoryItems)
self.dataSource.apply(snapshot, animatingDifferences: animating) {
print("applying snapshot completed!")
}
}
}
Ok it seems that i found the reason of all my errors with updating datasource by applying new snapshots
This lazy var dataSource is causing errors:
private(set) lazy var dataSource: UICollectionViewDiffableDataSource<Section, Item> = {
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView, cellProvider: cellProvider)
//dataSource.supplementaryViewProvider = supplementaryViewProvider
return dataSource
}()
I've changed it to
private(set) var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
and after configureCollectionView in viewDidLoad()
now I am calling configureDataSource() that does what was in lazy var initializer.

How to switch textFieldStyle to a TextField when user taps the field?

I'm trying to change the TextField style from .plain to .roundedCorners when the user taps on the TextField.
The TextField itself is initially disabled (.plain style) and when the user taps on it, should enable editing mode (which is working) and change to (.roundedCorners style)
I've tried changing the style based on TextField state (if disabled ? .plain : .roundedCorners), but that doesn't seem to be working
.textFieldStyle(self.listState.editingScreenshot == nil ? .plain : .roundedCorners)
I get the following error when using inline if statement:
Type 'StaticMember' has no member
'roundedCorners'.
Using style conditionally may be challenging, I prefer this approach, which is also much more customizable:
In this example I use a darker border color depending on activation, and in the second example, I just remove the style completely:
struct ContentView: View {
#State private var active1: Bool = false
#State private var value1 = ""
#State private var active2: Bool = false
#State private var value2 = ""
var body: some View {
VStack(alignment: .leading) {
Spacer()
Text("Field 1")
TextField("", text: $value1, onEditingChanged: { self.active1 = $0 }).padding().overlay(TextFieldBorder(rounded: active1))
Text("Field 2")
TextField("", text: $value2, onEditingChanged: { self.active2 = $0 }).padding().overlay(TextFieldBorder(rounded: active2))
Spacer()
}.background(Color(white: 0.9))
}
}
struct TextFieldBorder: View {
var rounded = true
var body: some View {
Group {
if rounded {
RoundedRectangle(cornerRadius: 10).stroke(Color.black)
} else {
RoundedRectangle(cornerRadius: 10).stroke(Color.gray)
}
}
}
}
To remove the style completely:
struct TextFieldBorder: View {
var rounded = true
var body: some View {
Group {
if rounded {
RoundedRectangle(cornerRadius: 10).stroke(Color.black)
} else {
RoundedRectangle(cornerRadius: 10).stroke(Color.clear)
}
}
}
}
The static member you are looking for is roundedBorder:
public static var roundedBorder: RoundedBorderTextFieldStyle.Member { get }

Is there any way to force execute the OnSizeAllocated method?

I have created a view using Xaml code behind. I did it using the code behind because I wanted to change the layout of the view based on the device orientation. So, the problem which I am facing is that the OnSizeAllocated method is being called after the view is loaded. So, it is unable to change the layout as per the device orientation. I just want to know if there is any way to invoke the OnSizeAllocated method before the view is loaded. Please click on the below link to view the code:
Please click Here to view the Code
1.Rearrange the Page
you could check if width is greater than height to determine if the device is now in landscape or portrait:
public partial class Page13 : ContentPage
{
private double _width ;
private double _height ;
private Grid grid;
private Label label;
private Entry entry;
private Button button;
public Page13 ()
{
_width = this.Width;
_height = this.Height;
label = new Label(){Text = "i am a laber"};
entry = new Entry(){WidthRequest = 200};
button = new Button(){Text = "Submit"};
grid = new Grid();
UpdateLayout();
StackLayout stackLayout = new StackLayout();
stackLayout.Children.Add(grid);
Content = stackLayout;
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (_width != width || _height != height)
{
_width = width;
_height = height;
UpdateLayout();
}
}
void UpdateLayout()
{
grid.RowDefinitions.Clear();
grid.ColumnDefinitions.Clear();
grid.Children.Clear();
if (_width > _height)
{
ScreenRotatedToLandscape();
}
else
{
ScreenRotatedToPortrait();
}
}
private void ScreenRotatedToLandscape()
{
grid.RowDefinitions.Add(new RowDefinition(){Height = new GridLength(1,GridUnitType.Auto)});
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
grid.ColumnDefinitions.Add(new ColumnDefinition(){Width = new GridLength(1,GridUnitType.Auto)});
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
grid.Children.Add(label,0,0);
grid.Children.Add(entry, 1, 0);
grid.Children.Add(button, 0, 1);
Grid.SetColumnSpan(button,2);
}
private void ScreenRotatedToPortrait()
{
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Auto) });
grid.Children.Add(label, 0, 0);
grid.Children.Add(entry, 0, 1);
grid.Children.Add(button, 0, 2);
}
}
This is the recommended implementation pulled right from the Xamarin.Forms documentation.
2.Using Xamarin.Essentials
It adds additional functionality to cross-platform applications built in Xamarin. One of these new features is the ability to ping the device for the current orientation by accessing the DeviceDisplay.ScreenMetrics.Orientation property. This returns the current device orientation, which can be used to determine which layout to render.
it's similar to the one above
private bool IsPortrait;
public Page13 ()
{
...
IsPortrait = DeviceDisplay.ScreenMetrics.Orientation == ScreenOrientation.Portrait;
UpdateLayout();
...
}
void UpdateLayout()
{
grid.RowDefinitions.Clear();
grid.ColumnDefinitions.Clear();
grid.Children.Clear();
if (IsPortrait)
{
ScreenRotatedToPortrait();
}
else
{
ScreenRotatedToLandscape();
}
}
You can't force run that since the SizeAllocation hasn't changed, but you could do this to get orientation on initial load:
If you add the Xamarin.Essentials nuget package, as you can see here, you can get the orientation using this line of code DeviceDisplay.MainDisplayInfo.Orientation and you will get Landscape, Portrait, Square, or Unknown.
If you don't want to add the package, you can just use Application.Current.MainPage.Width and Application.Current.MainPage.Height to figure out orientation.

Appending JsonFile (UrL) in array to display on application

I am trying to add my data from my Json file into the application.I want append the Authors name from the Json file into the empty array.
I have added all of the areas that needed to be added when i run the simulation i get an empty array. I need it display the Authors first name on the simulator.
Does anyone know what i need to do to my code to make it work?
My Code :
var AuthorGlobal = [String]()
class ViewController: UIViewController, UITextFieldDelegate{
#IBOutlet weak var DisplayAuthor: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
DisplayAuthor.text="\(AuthorGlobal)"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
Alamofire.request(.GET, "http://178.62.83.50/newsletters.json")
.responseJSON { response in
// print(response.request) // original URL request
// print(response.response) // URL response
// print(response.data) // server data
// print(response.result) // result of response serialization
if let _ = response.result.value {
// print("JSON: \(JSON)")
}
let json = JSON(data: response.data!)
if let Author = json["NewsLetter"][0]["Author"].string {
AuthorGlobal.append(Author)
}
if let LastName = json["NewsLetter"][0]["LastName"].string {
print(LastName)
}
if let ArticleTitle = json["NewsLetter"][0]["ArticleTitle"].string {
//Now you got your value
print(ArticleTitle)
}
if let Author = json["NewsLetter"][1]["Author"].string {
//Now you got your value
print(Author)
}
if let LastName = json["NewsLetter"][1]["LastName"].string {
//Now you got your value
print(LastName)
}
if let ArticleTitle = json["NewsLetter"][1]["ArticleTitle"].string {
//Now you got your value
print ("Article Title: " + (ArticleTitle))
}
}
}
I just tried by putting your json in my file system and loading it locally. Below is my code on Swift 2 and it all worked fine. You might want to check the JSON data coming correctly in your service call. Also, try to compare it line by line with my code to see if you missed out something. Its too late for me to call it a day so bear with me to not pointing out the exact root cause in your code!
var AuthorGlobal = [String]()
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var DisplayAuthor: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// DisplayAuthor.text="\(AuthorGlobal)"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
let filePath = NSBundle.mainBundle().pathForResource("1", ofType: "json")
var fileContents : String = ""
do {
fileContents = try String(contentsOfFile: filePath!, encoding: NSUTF8StringEncoding)
} catch (_) {
}
var json : Dictionary<String,Array<Dictionary<String,String>>> = Dictionary()
do {
json = try NSJSONSerialization.JSONObjectWithData(fileContents.dataUsingEncoding(NSUTF8StringEncoding)!, options:NSJSONReadingOptions.AllowFragments) as! Dictionary<String, Array<Dictionary<String, String>>>
} catch (_) {
}
let array = json["NewsLetter"] as Array?
if let author = array?[0]["Author"] {
AuthorGlobal.append(author)
}
print(AuthorGlobal) // This prints - ["Tom"]
if let LastName = array?[0]["LastName"] {
print(LastName) // This prints - Holton
}
if let ArticleTitle = array?[0]["ArticleTitle"] {
//Now you got your value
print(ArticleTitle) // This prints - XcodeGhost: Apple suffers a major malware infection inside the iOS app store.
}
if let Author = array?[1]["Author"] {
//Now you got your value
print(Author) // This prints - Sam
}
if let LastName = array?[1]["LastName"] {
//Now you got your value
print(LastName) // This prints - Devaney
}
if let ArticleTitle = array?[1]["ArticleTitle"] {
//Now you got your value
print ("Article Title: " + (ArticleTitle)) // This prints - Article Title: Google is 2 Billion Lines of Code
}
}
}

How to add css style to custom image node in JavaScript InfoVis ToolKit

I have created custom nodes for my force directed InfoVis graph in which I display a user's image. I want to now add style to the image, such as adding a border and making it a circle. I tried adding css class as follows, but it's not working.
img.className = myClass;
here's my custom node code:
//Custom nodes
$jit.ForceDirected.Plot.NodeTypes.implement({
'customImage':
{
'render': function (node, canvas)
{
var ctx = canvas.getCtx();
var img = new Image();
var pos = node.getPos();
img.onload = function ()
{
ctx.drawImage(img, pos.x - 16, pos.y - 16);
}
var n = _nodes[node.id];
if (n && n.imageUrl)
{
var size = 52;
var url = n.imageUrl.replace("{width}", size).replace("{height}", size);
img.src = url;
img.className = myClass;
}
else
{
img.src = '../Images/UserNoImage.png';
}
},
'contains': function (node, pos)
{
var npos = node.pos.getc(true),
dim = node.getData('dim');
return this.nodeHelper.square.contains(npos, pos, dim);
}
}
});
You can apply CSS styles to the html elements. The custom node which you have defined is simply drawing image on the canvas. The node does not correspond to any html element.
Hence before you call function drawImage you should make sure that the image is customized to your requirement, only then you call drawImage. In this case infovis does not know anything about css, all that it does is call drawImage which simply draws an image on the canvas.
Thus, the question you should tackle is, how do you apply css to the image so that its customized to your requirement. And this question is independent of infovis.