<!--
{
  "availability" : [
    "iOS: 7.0.0 -",
    "iPadOS: 7.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.0.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSAttributedString/data(from:documentAttributes:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSAttributedString(im)dataFromRange:documentAttributes:error:"
  },
  "title" : "data(from:documentAttributes:)"
}
-->

# data(from:documentAttributes:)

Returns a data object that contains a text stream corresponding to the characters and attributes within the specified range.

```
func data(from range: NSRange, documentAttributes dict: [NSAttributedString.DocumentAttributeKey : Any] = [:]) throws -> Data
```

## Parameters

`range`

The range.

`dict`

A required dictionary specifying the document attributes. The dictionary contains values from `Document Types` and must at least contain [`documentType`](/documentation/Foundation/NSAttributedString/DocumentAttributeKey/documentType).

## Return Value

Returns the data for the attributed string, or `nil` if failure. When `nil`, `error` encapsulates the error information.

## Discussion

Raises an [`rangeException`](/documentation/Foundation/NSExceptionName/rangeException) if any part of `range` lies beyond the end of the receiver’s characters.

> Handling Errors in Swift:
> In Swift, this method returns a nonoptional result and is marked with the `throws` keyword to indicate that it throws an error in cases of failure.
> 
> You call this method in a `try` expression and handle any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html) in [The Swift Programming Language](https://docs.swift.org/swift-book/) and `About Imported Cocoa Error Parameters`.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)